2

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()
virendra chaudhary
  • 179
  • 1
  • 2
  • 18

2 Answers2

4

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

Peter Thomas
  • 54,465
  • 21
  • 84
  • 248
  • 2
    But maintaining too many files of js will be overhead . Provided solution is also not a good approach in terms of readability. – virendra chaudhary Oct 29 '17 at 17:06
  • just create one feature file that has as many in-line JS functions as you want declared and re-use it. done ! – Peter Thomas Oct 29 '17 at 17:08
  • 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. – virendra chaudhary Oct 29 '17 at 17:40
  • 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 ? – Peter Thomas Oct 30 '17 at 05:56
  • 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. – MKod Aug 20 '18 at 10:48
  • @MKod how do you maintain the structure. Shall we keep all js files in classpath ? if i keep in a folder and give that folder name it gives error – Gaurav Khurana Mar 08 '21 at 15:08
0
* def data = karate.read('classpath:<path>/getRandomString.js')(<inputToTheFunctionIfAny>);

The above code works.

Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
  • 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](/help/how-to-answer). – Community Oct 05 '21 at 06:48