简体   繁体   中英

Karate - how to use variable in javascript functions parameter?

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)
* 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM