testingcucumberkarateoptional-parameters

How to match optional nested JSON objects in Karate


I'm trying to match a response that may have any of three optional keys that have the same JSON object schema but it doesn't seem like the optional syntax is working for this case. Does Karate support the kind of functionality I'm looking for? It works when all three schemas are present, but not when any of them are missing.

Scenario:
  * def schema_optional =
  """
  {
    "a": ##string,
    "b": ##number
  }
  """
  * def schema =
  """
  {
    "c": ##(schema_optional),
    "d": ##(schema_optional),
    "e": ##(schema_optional)
  }
  """
  * def result = 
  """
  {
    "d": {
      "a": "hi",
      "b": 19
    }
  }
  """
  * match result == schema

The error is

match failed: EQUALS
$ | not equal | actual does not contain key - 'c' (MAP:MAP)

Solution

  • Make this change - explained here: https://stackoverflow.com/a/78018894/143475

    * def schema_optional =
    """
    ({
      "a": '##string',
      "b": '##number'
    })
    """
    * def schema =
    """
    ({
      "c": '##(schema_optional)',
      "d": '##(schema_optional)',
      "e": '##(schema_optional)'
    })
    """
    * def result = 
    """
    {
      "d": {
        "a": "hi",
        "b": 19
      }
    }
    """
    * match result == schema