Karate - Conditional JSON schema validation

Viewed 353

I am just wondering how can I do conditional schema validation. The API response is dynamic based on customerType key. If customerType is person then, person details will be included and if the customerType is org organization details will be included in the JSON response. So the response can be in either of the following forms

{
    "customerType" : "person",
    "person" : {
        "fistName" : "A",
        "lastName" : "B"
    },
    "id" : 1,
    "requestDate" : "2021-11-11"
}

{
    "customerType" : "org",
    "organization" : {
        "orgName" : "A",
        "orgAddress" : "B"
    },
    "id" : 2,
    "requestDate" : "2021-11-11"
}

The schema I created to validate above 2 scenario is as follows

{
    "customerType" : "#string",
    "organization" : "#? response.customerType=='org' ? karate.match(_,personSchema) : karate.match(_,null)",
    "person" : "#? response.customerType=='person' ? karate.match(_,orgSchema) : karate.match(_,null)",
    "id" : "#number",
    "requestDate" : "#string"
}

but the schema fails to match with the actual response. What changes should I make in the schema to make it work?

Note : I am planning to reuse the schema in multiple tests so I will be keeping the schema in separate files, independent of the feature file
1 Answers

Can you refer to this answer which I think is the better approach: https://stackoverflow.com/a/47336682/143475

That said, I think you missed that the JS karate.match() API doesn't return a boolean, but a JSON that contains a pass boolean property.

So you have to do things like this:

* def someVar = karate.match(actual, expected).pass ? {} : {}
Related