|
| 1 | +/* |
| 2 | + * Copyright 2021 IceRock MAG Inc. Use of this source code is governed by the Apache 2.0 license. |
| 3 | + */ |
| 4 | + |
| 5 | +package dev.icerock.moko.javascript |
| 6 | + |
| 7 | +import kotlin.test.Test |
| 8 | +import kotlin.test.assertEquals |
| 9 | +import kotlinx.serialization.json.Json |
| 10 | +import kotlinx.serialization.json.encodeToJsonElement |
| 11 | + |
| 12 | +class JavaScriptEngineTest { |
| 13 | + @Test |
| 14 | + fun `test json context`() { |
| 15 | + val form = mapOf("selector_1" to "first_value", "selector_2" to "second_value") |
| 16 | + val profile = mapOf( "email" to "[email protected]") |
| 17 | + val formJson = Json.encodeToJsonElement(form) |
| 18 | + val profileJson = Json.encodeToJsonElement(profile) |
| 19 | + val context: Map<String, JsType> = mapOf("form" to JsType.Json(formJson), "profile" to JsType.Json(profileJson)) |
| 20 | + |
| 21 | + val jsEngine = JavaScriptEngine() |
| 22 | + |
| 23 | + assertEquals(JsType.Bool(true), jsEngine.evaluate(context = context, script = "form.selector_1 == \"first_value\"")) |
| 24 | + |
| 25 | + assertEquals(JsType.Bool(true), jsEngine.evaluate(context = context, script = "profile.email != null")) |
| 26 | + |
| 27 | + assertEquals( JsType. Str( "[email protected]"), jsEngine.evaluate(context = context, script = "profile.email")) |
| 28 | + |
| 29 | + assertEquals(JsType.Null, jsEngine.evaluate(context = context, script = "profile.first_name")) |
| 30 | + } |
| 31 | + |
| 32 | + @Test |
| 33 | + fun `test plus script`() { |
| 34 | + val list = listOf<Int>(5, 15) |
| 35 | + val listJson = Json.encodeToJsonElement(list) |
| 36 | + val context: Map<String, JsType> = mapOf("list" to JsType.Json(listJson), "number" to JsType.IntNum(4), "doubleString" to JsType.Str(" Hello ")) |
| 37 | + |
| 38 | + val jsEngine = JavaScriptEngine() |
| 39 | + |
| 40 | + assertEquals(JsType.DoubleNum(19.0), jsEngine.evaluate(context = context, script = "list[1]+number")) |
| 41 | + |
| 42 | + assertEquals(JsType.Str(" Hello 5"), jsEngine.evaluate(context = context, script = "doubleString+list[0]")) |
| 43 | + } |
| 44 | +} |
0 commit comments