Tips and Tricks - biswajitsundara/Karate GitHub Wiki

Request should be done before the POST

This is a common mistake people do often is writing request step after the POST step and that's not correct. We will have to place the request step before the POST step always. If we are declaring the header or param under background then that's fine however if we are keeping them in Scenario then have it before the POST

//Incorrect
Scenario:
    Given method POST
    When request jsonPayload

//Correct
Scenario:
    Given request jsonPayload
    When method POST

Single Space is Allowed

In Karate feature file when we put equals(=)or match(==) then remember to have only single space. If we put double space by mistake then it will throw the error that there's no matching step definition found.

//Incorrect (two spaces after = symbol)
* def expectedOutput  =  read('../data/result.json')

//Correct
* def expectedOutput = read('../data/result.json')

When we define variables using def then have a single space.

//Incorrect
*def expectedOutput=read('../data/result.json')

//Correct
* def expectedOutput = read('../data/result.json')

Call Functions

Most of the time we write the function under background but unless we call it, it won't have any effect. Also pass parameter as required by the functions.

Background:
    * def sleep =
      """
      function(seconds){
        for(i = 0; i <= seconds; i++)
        {
          java.lang.Thread.sleep(1*1000);
          karate.log(i);
        }
      }
      """
Scenario:
   -------
   * call sleep 10

Call another scenario from a scenario

First of all this is an anti pattern and never use it. Try other alternatives like background, karate config.js etc. However if we need to do it then this is the way.

//File name Sample.feature
Feature: Call one scenario into another

@tag1
Scenario:
   Given 'This is a test'

@tag2
Scenario:
   Given 'This is a test'
   And result = call read('Sample.feature@tag1')

Lets say if we have another feature file Sample1 under the same package and want to call a scenario from there, then use this approach just change the filename to Sample1

Compare all fields except one field

Lets say we have fetched the JSON response and we want to compare against a static file that we have. Also in this scenario we want to skip comparing some fields. Then we need to write #ignore as a value for those fields.

It will compare all fields except the ignore
"data": {
    "last_name": "Weaver",
    "id": "#ignore",
    "avatar": "https://reqres.in/img/faces/2-image.jpg",
    "first_name": "Janet",
    "email": "[email protected]"
  }
}
⚠️ **GitHub.com Fallback** ⚠️