4

I saw in the doc that it it possible to define a function in the background part and execute it after each scenario. see: https://github.com/intuit/karate/blob/master/karate-demo/src/test/java/demo/hooks/hooks.feature

But i need to send args to this function and don't find any solutions...

In the doc:

* configure afterScenario = 
"""
function(){
  var info = karate.info; 
  karate.log('after', info.scenarioType + ':', info.scenarioName);
  karate.call('after-scenario.feature', { caller: info.featureFileName });
}
"""

What i would like to do:

utils/js/afterFunc.js:

function fn(args){
  karate.log('after', args.msg);
}

myTest.feature:

* configure afterScenario = read('classpath:utils/js/afterFunc.js') {msg: 'Hello !'}

1 Answers1

2

The read function will read the afterFunc.js file, but it ignores the {msg: 'Hello !'} parameter.

Scripts can call other scripts but you don't want to call the script immediately, do you? You want to create a function reference and assign that reference to the afterScenario configuration.

But that's not enough. You want to curry the function - what is currying?

AFAIK this is not support by read directly.

There is a workaround. You can read the javascript file and create a function that calls your after-scenario-function with a parameter of your choice.

  Background:
    * def fn = read('classpath:after-scenario-with-params.js')
    * configure afterScenario =
    """
      function() {
        fn(karate.info, 'hello world');
      }
    """

The after-scenario-with-params.js contains the following js function:

function fn(info, someParameter) {
    karate.log('called after scenario:', info.scenarioName);
    karate.log('some parameter: ' + someParameter);
}

That's it.

I committed a complete running example to my karate sandbox repository. The repo is gradle and groovy based. I hope it helps.

Peter
  • 4,752
  • 2
  • 20
  • 32
  • 1
    It works perfectly, thank you for your answer ! FYI the naming of the function is important because if you call another .js file in one of the scenarios with a function also named "fn" in it, this workaround doesn't works anymore... – tabary Romain Apr 23 '19 at 19:20