Gaurav Kinra
Gaurav Kinra

Reputation: 203

How to call a Javascript function with arguments from .js file in karate feature file

Lets say I created javascript functions in functions js file.

function getReviews(reviews){
var length_reviews = reviews.length return length_reviews }

function getReviewsLength(reviewLength){
return reviewLength }

Here in function getReviews argument reviews is an array. Now how will I call getReviews function in one feature file. When I tried below code

* def jsFunction = call read('functions.js') * def review = jsFunction.getReviews(reviewFromFeatureFile) I am getting an error of

Cannot read property "length" from undefined

I already printed reviewFromFeatureFile and its coming correctly in print statement.

Upvotes: 4

Views: 7040

Answers (2)

Babu Sekaran
Babu Sekaran

Reputation: 4239

As Peter mentioned above you can keep you js inline on your feature

* def reviews = [{"r1":2},{"r1":3},{"r1":4}]
* def getReviews = function(reviews){ return reviews.length }
* def getReviewsLength = getReviews(reviews)
* print getReviewsLength

In this example, it should print 3.

For more other options for handling javascript or other reusable modules in karate, please refer to this article

Organizing re-usable functions in karate

Upvotes: 1

Peter Thomas
Peter Thomas

Reputation: 58153

In one "common" feature file, define multiple methods like this:

* def uuid = function(){ return java.util.UUID.randomUUID() + '' }
* def now = function(){ return java.lang.System.currentTimeMillis() }

You can now call this feature like this:

* call read('common.feature')

And now all the functions in that feature are available for use:

* def id = uuid()
* def time = now()

Upvotes: 0

Related Questions