78 lines
1.9 KiB
Go
78 lines
1.9 KiB
Go
package builtin
|
|
|
|
import (
|
|
"context"
|
|
"testing"
|
|
|
|
"github.com/stretchr/testify/assert"
|
|
"github.com/stretchr/testify/require"
|
|
|
|
"github.com/dop251/goja"
|
|
)
|
|
|
|
type TestArgs struct {
|
|
Field1 string `json:"field1"`
|
|
}
|
|
|
|
func (t TestArgs) Validate() error {
|
|
return nil
|
|
}
|
|
|
|
func TestAsyncBuiltin(t *testing.T) {
|
|
RegisterAsyncBuiltin[TestArgs, string]("testAsync", func(_ context.Context, args TestArgs) (string, error) {
|
|
return "result: " + args.Field1, nil
|
|
})
|
|
|
|
registryMutex.RLock()
|
|
builtin, ok := builtinRegistry["testAsync"]
|
|
registryMutex.RUnlock()
|
|
|
|
require.True(t, ok, "testAsync should be registered")
|
|
assert.Contains(t, builtin.Definition, "Promise<string>", "definition should include Promise<string>")
|
|
}
|
|
|
|
func TestAsyncBuiltinResolution(t *testing.T) {
|
|
RegisterAsyncBuiltin[TestArgs, string]("resolveTest", func(_ context.Context, args TestArgs) (string, error) {
|
|
return "test-result", nil
|
|
})
|
|
|
|
vm := goja.New()
|
|
RegisterBuiltins(vm)
|
|
|
|
result, err := vm.RunString(`resolveTest({field1: "hello"})`)
|
|
require.NoError(t, err)
|
|
|
|
promise, ok := result.Export().(*goja.Promise)
|
|
require.True(t, ok, "should return a Promise")
|
|
assert.NotNil(t, promise)
|
|
}
|
|
|
|
func TestAsyncBuiltinRejection(t *testing.T) {
|
|
RegisterAsyncBuiltin[TestArgs, string]("rejectTest", func(_ context.Context, args TestArgs) (string, error) {
|
|
return "", assert.AnError
|
|
})
|
|
|
|
vm := goja.New()
|
|
RegisterBuiltins(vm)
|
|
|
|
result, err := vm.RunString(`rejectTest({field1: "hello"})`)
|
|
require.NoError(t, err)
|
|
|
|
promise, ok := result.Export().(*goja.Promise)
|
|
require.True(t, ok, "should return a Promise")
|
|
assert.NotNil(t, promise)
|
|
}
|
|
|
|
func TestNonPromise(t *testing.T) {
|
|
RegisterBuiltin[TestArgs, string]("nonPromiseTest", func(_ context.Context, args TestArgs) (string, error) {
|
|
return "sync-result", nil
|
|
})
|
|
|
|
vm := goja.New()
|
|
RegisterBuiltins(vm)
|
|
|
|
result, err := vm.RunString(`nonPromiseTest({field1: "hello"})`)
|
|
require.NoError(t, err)
|
|
assert.Equal(t, "sync-result", result.Export())
|
|
}
|