MCPcopy Create free account
hub / github.com/buke/quickjs-go / TestModuleBuilder_Import

Function TestModuleBuilder_Import

module_test.go:406–492  ·  view source on GitHub ↗

============================================================================= MODULE IMPORT TESTS =============================================================================

(t *testing.T)

Source from the content-addressed store, hash-verified

404// =============================================================================
405
406func TestModuleBuilder_Import(t *testing.T) {
407 useStableOwnerHooksForLegacySubtests(t)
408
409 rt := NewRuntime()
410 defer rt.Close()
411 ctx := rt.NewContext()
412 defer ctx.Close()
413
414 t.Run("NamedImports", func(t *testing.T) {
415 greetFunc := ctx.NewFunction(func(ctx *Context, this *Value, args []*Value) *Value {
416 name := "World"
417 if len(args) > 0 {
418 name = args[0].ToString()
419 }
420 return ctx.NewString(fmt.Sprintf("Hello, %s!", name))
421 })
422
423 module := NewModuleBuilder("greeting").
424 Export("greet", greetFunc).
425 Export("defaultName", ctx.NewString("World"))
426
427 err := module.Build(ctx)
428 require.NoError(t, err)
429
430 result := ctx.Eval(`
431 (async function() {
432 const { greet, defaultName } = await import('greeting');
433 return greet('QuickJS');
434 })()
435 `, EvalAwait(true))
436 defer result.Free()
437
438 require.False(t, result.IsException())
439 require.Equal(t, "Hello, QuickJS!", result.ToString())
440 })
441
442 t.Run("FunctionImports", func(t *testing.T) {
443 calculateFunc := ctx.NewFunction(func(ctx *Context, this *Value, args []*Value) *Value {
444 if len(args) >= 2 {
445 a, b := args[0].ToFloat64(), args[1].ToFloat64()
446 return ctx.NewFloat64(a * b)
447 }
448 return ctx.NewFloat64(0)
449 })
450
451 module := NewModuleBuilder("calculator").
452 Export("multiply", calculateFunc).
453 Export("PI", ctx.NewFloat64(3.14159))
454
455 err := module.Build(ctx)
456 require.NoError(t, err)
457
458 result := ctx.Eval(`
459 (async function() {
460 const { multiply, PI } = await import('calculator');
461 return multiply(PI, 2);
462 })()
463 `, EvalAwait(true))

Callers

nothing calls this directly

Calls 15

CloseMethod · 0.95
NewContextMethod · 0.95
CloseMethod · 0.95
NewFunctionMethod · 0.95
NewStringMethod · 0.95
EvalMethod · 0.95
NewFloat64Method · 0.95
NewBoolMethod · 0.95
NewRuntimeFunction · 0.85
NewModuleBuilderFunction · 0.85
EvalAwaitFunction · 0.85

Tested by

no test coverage detected