Karate: Unable to move schema definition out of feature file

Viewed 25

I'm able to successfully run the Feature/scenario, When I define the schema inside my feature file .

Here is a simplified example of the schema.

Background:
  ...
  ...
  * def accountSchema = { id: '#number? _ >= 0', prop1: '#number? _ >= 0', prop2: '#string', prop3: '#string', optionaProp: '##string'  }
  * def userAccountsSchema = ({ entitledAccounts: '#[] accountSchema',  prop5: '#number' , prop6: '##string'})

And here is how I'm validating

Scenario:
  ...
  ...
  When method GET
  Then status 200
  * print userAccountsSchema 
  And match response == userAccountsSchema

But the schema I posted here is simplified to ask this question, the real schema is far more complex. So for clarity purpose, I decided to put schema in a separate js file response-schemas.js under the same folder as the feature file.

Here is the simplified content of response-schemas.js file.

function schema () {
    let accountSchema = {

       id: '#number? _ >= 0',
       prop1: '#number? _ >= 0',

       prop2: '#string',
       prop3: '#string',
     
      optionaProp: '##string',
    }'

    return {
            accounts: `#[] ${accountSchema}` ,
            prop5: '#string',
            prop6: '#string',
    };
}

now if I replace the 2 lines I mentioned at the beginning of the question under Background:, with below line

 * def userAccountsSchema = call read('response-schemas.js')

I get this error

And match response == schemas
SyntaxError: Unnamed:1:8 Expected comma but found ident
[object Object]
        ^

I believe, I understand the problem, is this line

 accounts: `#[] ${accountSchema}` ,

but unable to figure out the solution. If I tried to change the accountSchema variable in response-schemas.js to use multiline string then I get error in read step in Background

the whole idea to have a dedicated js file for schema is to keep it readable (by using multiple lines, preferably objects not a long string)

1 Answers

The main problem is this part:

accounts: `#[] ${accountSchema}`

Where you are trying to stuff a JSON into the Karate "fuzzy" expression. This is just not supported. Note that the Karate way of defining things like #(foo) and #[] bar has nothing to do with JavaScript, so I recommend not mixing these.

I know there is a desire to achieve the match in just one-line and somehow get one monstrous schema to do everything and I very strongly discourage this. Split your assertions into multiple lines. Split your response into smaller chunks of JSON if needed. There is nothing wrong with that. This also makes the life much easier of people who come along later who have to maintain your test.

For ideas see this answer: https://stackoverflow.com/a/61252709/143475

Other answers: https://stackoverflow.com/search?q=%5Bkarate%5D+array+schema

Tip: you can keep your schema "chunks" as JSON files if needed.

Related