============================================================================= MODULE IMPORT TESTS =============================================================================
(t *testing.T)
| 404 | // ============================================================================= |
| 405 | |
| 406 | func 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)) |
nothing calls this directly
no test coverage detected