summaryrefslogtreecommitdiff
path: root/examples/scala-js/test-suite/src/test/scala/scala/scalajs/testsuite/jsinterop/DynamicTest.scala
blob: 2b6942fcc0ecbefc270f2e37a020d4c3d5c100ac (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
/*                     __                                               *\
**     ________ ___   / /  ___      __ ____  Scala.js Test Suite        **
**    / __/ __// _ | / /  / _ | __ / // __/  (c) 2013, LAMP/EPFL        **
**  __\ \/ /__/ __ |/ /__/ __ |/_// /_\ \    http://scala-js.org/       **
** /____/\___/_/ |_/____/_/ | |__/ /____/                               **
**                          |/____/                                     **
\*                                                                      */
package scala.scalajs.testsuite.jsinterop

import scala.scalajs.js
import org.scalajs.jasminetest.JasmineTest

import js.annotation.JSExport

object DynamicTest extends JasmineTest {

  describe("scala.scalajs.js.Dynamic") {

    it("should workaround Scala 2.10 issue with implicit conversion for dynamic fields named x - #8") {
      class Point(val x: Int, val y: Int)

      def jsonToPoint(json: js.Dynamic) = {
        new Point(json.x.toString.toInt, json.y.toString.toInt)
      }

      val json = js.eval("var dynamicTestPoint = { x: 1, y: 2 }; dynamicTestPoint;")
      val point = jsonToPoint(json.asInstanceOf[js.Dynamic])

      expect(point.x).toEqual(1)
      expect(point.y).toEqual(2)
    }

    it("should allow to call functions with arguments named x") {
      class A {
        def a = 1
      }

      class B extends A {
        @JSExport
        def x(par: Int) = a + par // make sure `this` is bound correctly in JS
      }

      val b = (new B).asInstanceOf[js.Dynamic]

      expect(b.x(10)).toEqual(11)
    }

    it("should allow instanciating JS classes dynamically - #10") {
      val DynamicTestClass = js.eval("""
          var DynamicTestClass = function(x) {
            this.x = x;
          };
          DynamicTestClass;
          """).asInstanceOf[js.Dynamic]
      val obj = js.Dynamic.newInstance(DynamicTestClass)("Scala.js")
      expect(obj.x).toEqual("Scala.js")
    }

    it("should allow instantiating JS classes dynamically with varargs - #708") {
      val DynamicTestClassVarArgs = js.eval("""
          var DynamicTestClassVarArgs = function() {
            this.count = arguments.length;
            for (var i = 0; i < arguments.length; i++)
              this['elem'+i] = arguments[i];
          };
          DynamicTestClassVarArgs;
          """).asInstanceOf[js.Dynamic]

      val obj1 = js.Dynamic.newInstance(DynamicTestClassVarArgs)("Scala.js")
      expect(obj1.count).toEqual(1)
      expect(obj1.elem0).toEqual("Scala.js")

      val obj2 = js.Dynamic.newInstance(DynamicTestClassVarArgs)(
          "Scala.js", 42, true)
      expect(obj2.count).toEqual(3)
      expect(obj2.elem0).toEqual("Scala.js")
      expect(obj2.elem1).toEqual(42)
      expect(obj2.elem2).toEqual(true)

      def obj3Args: Seq[js.Any] = Seq("Scala.js", 42, true)
      val obj3 = js.Dynamic.newInstance(DynamicTestClassVarArgs)(obj3Args: _*)
      expect(obj3.count).toEqual(3)
      expect(obj3.elem0).toEqual("Scala.js")
      expect(obj3.elem1).toEqual(42)
      expect(obj3.elem2).toEqual(true)
    }

    it("should provide an object literal construction") {
      import js.Dynamic.{ literal => obj }
      val x = obj(foo = 3, bar = "foobar")
      expect(x.foo).toEqual(3)
      expect(x.bar).toEqual("foobar")
      expect(x.unknown).toBeUndefined()

      val y = obj(
          inner = obj(name = "inner obj"),
          fun = { () => 42 }
      )
      expect(y.inner.name).toEqual("inner obj")
      expect(y.fun()).toEqual(42)

      expect(obj().anything).toBeUndefined()
    }

    it("should provide object literal construction with dynamic naming") {
      import js.Dynamic.{ literal => obj }
      val x = obj("foo" -> 3, "bar" -> "foobar")
      expect(x.foo).toEqual(3)
      expect(x.bar).toEqual("foobar")
      expect(x.unknown).toBeUndefined()

      val tup1 = ("hello1", 3: js.Any)
      val tup2 = ("hello2", 10: js.Any)

      val y = obj(tup1, tup2)
      expect(y.hello1).toEqual(3)
      expect(y.hello2).toEqual(10)

      var count = 0
      val z = obj({ count += 1; ("foo", "bar")})
      expect(z.foo).toEqual("bar")
      expect(count).toEqual(1)
    }

    it("should allow to create an empty object with the literal syntax") {
      import js.Dynamic.{ literal => obj }
      val x = obj()
      expect(x.isInstanceOf[js.Object]).toBeTruthy()
    }

    it("should properly encode object literal property names") {
      import js.Dynamic.{ literal => obj }

      val obj0 = obj("3-" -> 42)
      expect(obj0.`3-`).toEqual(42)

      val obj0Dict = obj0.asInstanceOf[js.Dictionary[js.Any]]
      expect(obj0Dict("3-")).toEqual(42)

      val checkEvilProperties = js.eval("""
        function dynamicLiteralNameEncoding_checkEvilProperties(x) {
          return x['.o[3√!|-pr()per7:3$];'] === ' such eval ';
        }
        dynamicLiteralNameEncoding_checkEvilProperties
      """).asInstanceOf[js.Function1[js.Any, Boolean]]
      val obj1 = obj(
          ".o[3√!|-pr()per7:3$];" -> " such eval ").asInstanceOf[js.Dictionary[js.Any]]
      expect(obj1(".o[3√!|-pr()per7:3$];")).toEqual(" such eval ")
      expect(checkEvilProperties(obj1)).toEqual(true)

      val checkQuotesProperty = js.eval("""
        function dynamicLiteralNameEncoding_quote(x) {
          return x["'" + '"'] === 7357;
        }
        dynamicLiteralNameEncoding_quote
      """).asInstanceOf[js.Function1[js.Any, Boolean]]

      val quote = '"'

      Seq(
        obj("'" + quote -> 7357),
        obj(s"'$quote" -> 7357),
        obj("'\"" -> 7357),
        obj("'" + quote -> 7357)
      ).foreach { o =>
        val dict = o.asInstanceOf[js.Dictionary[js.Any]]
        expect(dict("'\"")).toEqual(7357)
        expect(dict("'" + quote)).toEqual(7357)
        expect(dict(s"'$quote")).toEqual(7357)
        expect(checkQuotesProperty(o)).toEqual(true)
      }
    }

    it("should return subclasses of js.Object in literal construction - #783") {
      import js.Dynamic.{ literal => obj }

      val a: js.Object = obj(theValue = 1)
      expect(a.hasOwnProperty("theValue")).toBeTruthy
      expect(a.hasOwnProperty("noValue")).toBeFalsy

      val b: js.Object = obj("theValue" -> 2)
      expect(b.hasOwnProperty("theValue")).toBeTruthy
      expect(b.hasOwnProperty("noValue")).toBeFalsy

    }
  }
}