08 Java Script Functions - biswajitsundara/Karate GitHub Wiki
Sometimes we would need to manipulate data before or after karate scenario steps and java script functions help us in doing so. This helps us to perform different types of validations.
Scenario: Get call test with Single line function
Given path '/api/users/2'
When method GET
Then status=200
* def myFun = function(){return "Hello"}
* def returnedData = call myFun
Then print 'returned data ==>'+returnedData
Scenario: Get call test with Block function
Given path '/api/users/2'
When method GET
Then status=200
* def myFun2 =
"""
function(){
return "Hey"
}
"""
* def returnedData2 = call myFun2
Then print 'returned data ==>'+returnedData2
Scenario: Number of user validation
Given path '/api/users?page=2'
When method GET
Then status=200
* def data = response.data
And print data
* def valFun =
"""
function(arg){
return arg.length;
}
"""
* def numberOfUsers = call valFun data
Then print numberOfUsers
And match numberOfUsers == 6
Scenario: Print only user ids
Given path '/api/users?page=2'
When method GET
Then status=200
* def data2 = response.data
And print data2
* def valFun2 =
"""
function(arg){
arrIds = [];
for(i=0;i<arg.length;i++){
arrIds.push(arg[i].id);
}
return arrIds;
}
"""
* def idOfUsers = call valFun2 data2
Then print idOfUsers
Scenario: Print details for user 5
Given path '/api/users?page=2'
When method GET
Then status=200
* def data1 = response.data
And print data1
* def valFun1 =
"""
function(arg){
for(i=0;i<arg.length;i++){
if(arg[i].id==5){
return arg[i]
}
}
}
"""
* def user5 = call valFun1 data1
Then print user5