forked from dop251/goja
-
Notifications
You must be signed in to change notification settings - Fork 0
/
func_test.go
106 lines (94 loc) · 1.79 KB
/
func_test.go
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
package goja
import (
"fmt"
"reflect"
"testing"
)
func TestFuncProto(t *testing.T) {
const SCRIPT = `
"use strict";
function A() {}
A.__proto__ = Object;
A.prototype = {};
function B() {}
B.__proto__ = Object.create(null);
var thrown = false;
try {
delete B.prototype;
} catch (e) {
thrown = e instanceof TypeError;
}
thrown;
`
testScript(SCRIPT, valueTrue, t)
}
func TestFuncPrototypeRedefine(t *testing.T) {
const SCRIPT = `
let thrown = false;
try {
Object.defineProperty(function() {}, "prototype", {
set: function(_value) {},
});
} catch (e) {
if (e instanceof TypeError) {
thrown = true;
} else {
throw e;
}
}
thrown;
`
testScript(SCRIPT, valueTrue, t)
}
func TestFuncExport(t *testing.T) {
vm := New()
typ := reflect.TypeOf((func(FunctionCall) Value)(nil))
f := func(expr string, t *testing.T) {
v, err := vm.RunString(expr)
if err != nil {
t.Fatal(err)
}
if actualTyp := v.ExportType(); actualTyp != typ {
t.Fatalf("Invalid export type: %v", actualTyp)
}
ev := v.Export()
if actualTyp := reflect.TypeOf(ev); actualTyp != typ {
t.Fatalf("Invalid export value: %v", ev)
}
}
t.Run("regular function", func(t *testing.T) {
f("(function() {})", t)
})
t.Run("arrow function", func(t *testing.T) {
f("(()=>{})", t)
})
t.Run("method", func(t *testing.T) {
f("({m() {}}).m", t)
})
t.Run("class", func(t *testing.T) {
f("(class {})", t)
})
}
func ExampleAssertConstructor() {
vm := New()
res, err := vm.RunString(`
(class C {
constructor(x) {
this.x = x;
}
})
`)
if err != nil {
panic(err)
}
if ctor, ok := AssertConstructor(res); ok {
obj, err := ctor(nil, vm.ToValue("Test"))
if err != nil {
panic(err)
}
fmt.Print(obj.Get("x"))
} else {
panic("Not a constructor")
}
// Output: Test
}