|
| 1 | +// Copyright 2021 Roger Chapman and the v8go contributors. All rights reserved. |
| 2 | +// Use of this source code is governed by a BSD-style license that can be |
| 3 | +// found in the LICENSE file. |
| 4 | + |
| 5 | +package v8go_test |
| 6 | + |
| 7 | +import ( |
| 8 | +"testing" |
| 9 | + |
| 10 | +"rogchap.com/v8go" |
| 11 | +) |
| 12 | + |
| 13 | +func TestFunctionCall(t *testing.T) { |
| 14 | +t.Parallel() |
| 15 | + |
| 16 | +ctx, err := v8go.NewContext() |
| 17 | +failIf(t, err) |
| 18 | +_, err = ctx.RunScript("function add(a, b) { return a + b; }", "") |
| 19 | +failIf(t, err) |
| 20 | +addValue, err := ctx.Global().Get("add") |
| 21 | +failIf(t, err) |
| 22 | +iso, _ := ctx.Isolate() |
| 23 | + |
| 24 | +arg1, err := v8go.NewValue(iso, int32(1)) |
| 25 | +failIf(t, err) |
| 26 | + |
| 27 | +fn, _ := addValue.AsFunction() |
| 28 | +resultValue, err := fn.Call(arg1, arg1) |
| 29 | +failIf(t, err) |
| 30 | + |
| 31 | +if resultValue.Int32() != 2 { |
| 32 | +t.Errorf("expected 1 + 1 = 2, got: %v", resultValue.DetailString()) |
| 33 | +} |
| 34 | +} |
| 35 | + |
| 36 | +func TestFunctionCallError(t *testing.T) { |
| 37 | +t.Parallel() |
| 38 | + |
| 39 | +ctx, err := v8go.NewContext() |
| 40 | +failIf(t, err) |
| 41 | +_, err = ctx.RunScript("function throws() { throw 'error'; }", "script.js") |
| 42 | +failIf(t, err) |
| 43 | +addValue, err := ctx.Global().Get("throws") |
| 44 | +failIf(t, err) |
| 45 | + |
| 46 | +fn, _ := addValue.AsFunction() |
| 47 | +_, err = fn.Call() |
| 48 | +if err == nil { |
| 49 | +t.Errorf("expected an error, got none") |
| 50 | +} |
| 51 | +got := *(err.(*v8go.JSError)) |
| 52 | +want := v8go.JSError{Message: "error", Location: "script.js:1:21"} |
| 53 | +if got != want { |
| 54 | +t.Errorf("want %+v, got: %+v", want, got) |
| 55 | +} |
| 56 | +} |
| 57 | + |
| 58 | +func failIf(t *testing.T, err error) { |
| 59 | +t.Helper() |
| 60 | +if err != nil { |
| 61 | +t.Fatal(err) |
| 62 | +} |
| 63 | +} |
0 commit comments