Skip to content

Commit

Permalink
js: Use the newly extracted module system in tests
Browse files Browse the repository at this point in the history
This is the main place where the module system being available
and working the same in tests as it does when k6 runs is really
important for the test itself.
  • Loading branch information
mstoykov committed Apr 27, 2023
1 parent 2ea5674 commit 6680534
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 11 deletions.
19 changes: 8 additions & 11 deletions js/modules/k6/experimental/tracing/module_test.go
Expand Up @@ -3,7 +3,6 @@ package tracing
import (
"testing"

"github.com/dop251/goja"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.k6.io/k6/js/modules/k6/http"
Expand Down Expand Up @@ -59,16 +58,14 @@ type testSetup struct {

func newTestSetup(t *testing.T) testSetup {
ts := modulestest.NewRuntime(t)
m := new(RootModule).NewModuleInstance(ts.VU)

rt := ts.VU.Runtime()
require.NoError(t, rt.Set("instrumentHTTP", m.Exports().Named["instrumentHTTP"]))

export := http.New().NewModuleInstance(ts.VU).Exports().Default
require.NoError(t, rt.Set("require", func(module string) *goja.Object {
require.Equal(t, "k6/http", module)
return rt.ToValue(export).ToObject(rt)
}))
err := ts.SetupModuleSystem(map[string]interface{}{
"k6/http": http.New(),
"k6/experimental/tracing": new(RootModule),
}, nil)
require.NoError(t, err)

_, err = ts.VU.Runtime().RunString("var instrumentHTTP = require('k6/experimental/tracing').instrumentHTTP")
require.NoError(t, err)

return testSetup{
t: t,
Expand Down
11 changes: 11 additions & 0 deletions js/modulestest/runtime.go
Expand Up @@ -3,11 +3,13 @@ package modulestest

import (
"context"
"net/url"
"testing"

"github.com/dop251/goja"
"go.k6.io/k6/js/common"
"go.k6.io/k6/js/eventloop"
"go.k6.io/k6/js/modules"
"go.k6.io/k6/lib"
"go.k6.io/k6/lib/testutils"
"go.k6.io/k6/metrics"
Expand Down Expand Up @@ -55,3 +57,12 @@ func (r *Runtime) MoveToVUContext(state *lib.State) {
r.VU.InitEnvField = nil
r.VU.StateField = state
}

// SetupModuleSystem setups the modules system for the current Runtime
// see [modules.NewModuleResolver] for the meaining of the parameters
func (r *Runtime) SetupModuleSystem(goModules map[string]interface{}, loader modules.CJSModuleLoader) error {
mr := modules.NewModuleResolver(goModules, loader)
ms := modules.NewModuleSystem(mr, r.VU)
impl := modules.NewOldRequireImpl(r.VU, ms, url.URL{})
return r.VU.RuntimeField.Set("require", impl.Require)
}

0 comments on commit 6680534

Please sign in to comment.