Search code examples
karategherkin

Is there a if functionality in Karate framework?


Here is the sample code

"xNotification": [
      {
        "code": "1234",
        "text": "Invalid Data"
        "yNotification": [
          {
            "code": "345",
            "text": "Invalid Data"
          }
        ]
      }
   ]
 }

yNotification array only exits sometimes in the response, when it exists I need to capture the code value and put it in a variable. I don't want assert just when it exists I need to put it in a variable. I am newbie to any testing frameworks. I appreciate any help with this issue. Thanks in advance.


Solution

  • Please read this part of the documentation: https://github.com/intuit/karate#conditional-logic

    Example:

    * def expected = zone == 'zone1' ? { foo: '#string' } : { bar: '#number' }
    * match response == expected
    

    EDIT: This is the complete solution to your question:

    * def response =
    """
    { "xNotification": [
          {
            "code": "1234",
            "text": "Invalid Data",
            "yNotification": [
              {
                "code": "345",
                "text": "Invalid Data"
              }
            ]
          }
       ]
    }
    """
    * def code = karate.get('$.xNotification[0].yNotification[0].code')
    * print code