go.ketch.com/lib/goja@v0.0.1/func_test.go (about) 1 package goja 2 3 import ( 4 "fmt" 5 "reflect" 6 "testing" 7 ) 8 9 func TestFuncProto(t *testing.T) { 10 const SCRIPT = ` 11 "use strict"; 12 function A() {} 13 A.__proto__ = Object; 14 A.prototype = {}; 15 16 function B() {} 17 B.__proto__ = Object.create(null); 18 var thrown = false; 19 try { 20 delete B.prototype; 21 } catch (e) { 22 thrown = e instanceof TypeError; 23 } 24 thrown; 25 ` 26 testScript(SCRIPT, valueTrue, t) 27 } 28 29 func TestFuncPrototypeRedefine(t *testing.T) { 30 const SCRIPT = ` 31 let thrown = false; 32 try { 33 Object.defineProperty(function() {}, "prototype", { 34 set: function(_value) {}, 35 }); 36 } catch (e) { 37 if (e instanceof TypeError) { 38 thrown = true; 39 } else { 40 throw e; 41 } 42 } 43 thrown; 44 ` 45 46 testScript(SCRIPT, valueTrue, t) 47 } 48 49 func TestFuncExport(t *testing.T) { 50 vm := New() 51 typ := reflect.TypeOf((func(FunctionCall) Value)(nil)) 52 53 f := func(expr string, t *testing.T) { 54 v, err := vm.RunString(expr) 55 if err != nil { 56 t.Fatal(err) 57 } 58 if actualTyp := v.ExportType(); actualTyp != typ { 59 t.Fatalf("Invalid export type: %v", actualTyp) 60 } 61 ev := v.Export() 62 if actualTyp := reflect.TypeOf(ev); actualTyp != typ { 63 t.Fatalf("Invalid export value: %v", ev) 64 } 65 } 66 67 t.Run("regular function", func(t *testing.T) { 68 f("(function() {})", t) 69 }) 70 71 t.Run("arrow function", func(t *testing.T) { 72 f("(()=>{})", t) 73 }) 74 75 t.Run("method", func(t *testing.T) { 76 f("({m() {}}).m", t) 77 }) 78 79 t.Run("class", func(t *testing.T) { 80 f("(class {})", t) 81 }) 82 } 83 84 func ExampleAssertConstructor() { 85 vm := New() 86 res, err := vm.RunString(` 87 (class C { 88 constructor(x) { 89 this.x = x; 90 } 91 }) 92 `) 93 if err != nil { 94 panic(err) 95 } 96 if ctor, ok := AssertConstructor(res); ok { 97 obj, err := ctor(nil, vm.ToValue("Test")) 98 if err != nil { 99 panic(err) 100 } 101 fmt.Print(obj.Get("x")) 102 } else { 103 panic("Not a constructor") 104 } 105 // Output: Test 106 }