Karate - how to use variable in javascript functions parameter?

Viewed 96

I see https://karatelabs.github.io/karate/#javascript-functions

* def greeter = function(title, name) { return 'hello ' + title + ' ' + name }
* assert greeter('Mr.', 'Bob') == 'hello Mr. Bob'

but I need use a variable.

* def greeter = function(title, name) { return 'hello ' + title + ' ' + name }
* assert greeter('Mr.', #(myvartitle)) == 'hello Mr. Bob'

my console error is:

[ERROR] Failures:
[ERROR]   MyWebsiteRunner js failed:
>>>>
01: greeter('Mr.', #(myvartitle)) == 'hello Mr. Bob'
<<<<
org.graalvm.polyglot.PolyglotException: SyntaxError: Unnamed:1:15 Expected an operand but found error
greeter('Mr.', #(myvartitle)) == 'hello Mr. Bob'
               ^

- org.graalvm.polyglot.Context.eval(Context.java:401)
- com.intuit.karate.graal.JsEngine.evalForValue(JsEngine.java:141)
- com.intuit.karate.graal.JsEngine.eval(JsEngine.java:137)
- com.intuit.karate.core.ScenarioEngine.evalJs(ScenarioEngine.java:1252)
- com.intuit.karate.core.ScenarioEngine.assertTrue(ScenarioEngine.java:232)
- com.intuit.karate.ScenarioActions.assertTrue(ScenarioActions.java:242)
- java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
2 Answers
* def greeter = function(title, name) { return 'hello ' + title + ' ' + name }
* assert greeter('Mr.', myvartitle) == 'hello Mr. Bob'

The #(foo) syntax is only for JSON: https://github.com/karatelabs/karate#rules-for-embedded-expressions

All you need to know is that Karate is a thin wrapper over JS. So variables, "just work".

Try:

* assert greeter('Mr.', myvartitle) == 'hello Mr. Bob'

To put it another way, anything within round-brackets is treated as JavaScript.

Related