1

I have multiple scenarios in a feature file. At the end of each scenario, I need to "clean up" before the start of the next scenario. My clean up function requires a json object to be passed in. Each scenario has a different object. Therefore, I need to use embedded expression, so dynamic data gets erased.

My setup is like this:

        * configure afterScenario = 
        """
        function(){
          var deleteData = { customerData: '#(portfolio)' };
          karate.call(deleteData.feature@deletePortfolio', deleteData);
        }

And scenario may look something like this:

        // here we get a brand new, unused "portfolio" value from a related function.
        * table customer1
            |portfolio  | status |
            |portfolio  | 200    |
        * call read(random.feature@random) customer1

So at the end of the above scenario, I expect the afterScenario to kick in and delete the "portfolio" variable value for that scenario. However, because it's a Java interop inside the afterScenario block, it doesn't recognize Karate's embedded expressions. Any way around this?

hungryhippos
  • 617
  • 4
  • 15

1 Answers1

1

The moment you are within a JS block, you are "out" of Karate. So embedded expressions don't work, but "JS style" expressions work.

Read this once to be more clear about this: https://github.com/karatelabs/karate#karate-expressions

So this will work:

* configure afterScenario = 
    """
    function(){
      var deleteData = { customerData: portfolio };
      karate.call('deleteData.feature@deletePortfolio', deleteData);
    }

Or even:

* configure afterScenario = function(){ karate.call('deleteData.feature@deletePortfolio', { customerData: portfolio }) }

One more tip, karate.get('someVariableName') can get you the value of any variable, any time.

And I do think you are over-engineering your tests, please don't:

https://stackoverflow.com/a/46080568/143475

https://stackoverflow.com/a/60944060/143475

https://stackoverflow.com/a/54126724/143475

Peter Thomas
  • 54,465
  • 21
  • 84
  • 248
  • Hey, so, the Karate page says: "embedded expressions will be evaluated even when you read() from a JSON or XML file." It also says, in the "Karate object" section for karate.read(): "the same read() function" with a link to the core Karate read() function. So that's not quite accurate, because you say here that JS-side karate.read() isn't actually the same function as the gherkin-side read(). "For JSON and XML files, Karate will evaluate any embedded expressions on load. ...it is internally implemented as a JavaScript function" – Keith Tyler Mar 18 '22 at 23:35
  • @KeithTyler I'm sorry I don't follow. if you can replicate the "problem" you refer to following these instructions I can take a look: https://github.com/karatelabs/karate/wiki/How-to-Submit-an-Issue - of course if you submit a PR to "fix" the docs or anything else, that is very much preferred – Peter Thomas Mar 19 '22 at 04:31