3

Suppose I have saved followings functions in a Utility js file.

function getCurrentDate(){
return 'date';
}

function getMonth(){

return 'Oct';
}

Please help me how any of these methods can be accessed in feature file.

I tried following code but it is not working.

* def fun = call read('Utility.js')

* def result = getData()
or
* def result = fun.getData()
0

2 Answers 2

7

In Karate, a JS file can contain only one function and it does not need a name, take a closer look at the examples.

I don't really recommend combining multiple functions into one file, it just makes things much harder to maintain. But if you really insist, here's how:

function() {
  return {
    getCurrentDate: function(){ return 'date' },
    getMonth: function(){ return 'month' }
  }
}

EDIT: a much better answer is here: https://stackoverflow.com/a/49384760/143475

Sign up to request clarification or add additional context in comments.

6 Comments

But maintaining too many files of js will be overhead . Provided solution is also not a good approach in terms of readability.
just create one feature file that has as many in-line JS functions as you want declared and re-use it. done !
Feature file will also be fine. However , do we have any way to reuse particular function from a feature file having many java script function? I have checked documentation but not able to figure it out.
really not sure what you are concerned about, split your features depending on what you want to re-use. if some JS is declared and not used, it is ok, why are you worried ?
You can call def functions = call read('classpath:reusable.js') and in same feature file try def x = functions.getCurrentDate( ). Hope this helps others trying to figure out on calling custom functions that are in javascript file.
|
0
* def data = karate.read('classpath:<path>/getRandomString.js')(<inputToTheFunctionIfAny>);

The above code works.

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.