From 2b8482564706a87314b14b0ada6e2e0ffb7c343b Mon Sep 17 00:00:00 2001 From: oleiade Date: Mon, 10 Jul 2023 13:54:42 +0200 Subject: [PATCH] Add a `RunOnEventLoop` method to modulestest.Runtime --- js/modulestest/runtime.go | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/js/modulestest/runtime.go b/js/modulestest/runtime.go index 0cfbedba5c05..a3842e39e653 100644 --- a/js/modulestest/runtime.go +++ b/js/modulestest/runtime.go @@ -74,6 +74,34 @@ func (r *Runtime) SetupModuleSystemFromAnother(another *Runtime) error { return r.innerSetupModuleSystem() } +// RunOnEventLoop will run the given code on the event loop. +// +// It is meant as a helper to test code that is expected to be run on the event loop, such +// as code that returns a promise. +// +// A typical usage is to facilitate writing testsĀ for asynchrounous code: +// +// func TestSomething(t *testing.T) { +// runtime := modulestest.NewRuntime(t) +// +// err := runtime.RunOnEventLoop(` +// doSomethingAsync().then(() => { +// // do some assertions +// }); +// `) +// require.NoError(t, err) +// } +func (r *Runtime) RunOnEventLoop(code string) error { + err := r.EventLoop.Start(func() error { + _, err := r.VU.Runtime().RunString(code) + return err + }) + + r.EventLoop.WaitOnRegistered() + + return err +} + func (r *Runtime) innerSetupModuleSystem() error { ms := modules.NewModuleSystem(r.mr, r.VU) impl := modules.NewLegacyRequireImpl(r.VU, ms, url.URL{})