diff --git a/js/modules/k6/timers/timers.go b/js/modules/k6/timers/timers.go index 6a257a17b61..0c1879b90ae 100644 --- a/js/modules/k6/timers/timers.go +++ b/js/modules/k6/timers/timers.go @@ -2,12 +2,14 @@ package timers import ( + "fmt" "time" "github.com/mstoykov/k6-taskqueue-lib/taskqueue" "github.com/sirupsen/logrus" "github.com/grafana/sobek" + "go.k6.io/k6/js/common" "go.k6.io/k6/js/modules" ) @@ -126,6 +128,15 @@ func (e *Timers) timerInitialization( timeout = 0 } + name := setTimeoutName + if repeat { + name = setIntervalName + } + + if callback == nil { + common.Throw(e.vu.Runtime(), fmt.Errorf("%s's callback isn't a callable function", name)) + } + task := func() error { // Specification 8.1: If id does not exist in global's map of active timers, then abort these steps. if _, exist := e.timers[id]; !exist { @@ -147,11 +158,6 @@ func (e *Timers) timerInitialization( return err } - name := setTimeoutName - if repeat { - name = setIntervalName - } - e.runAfterTimeout(&timer{ id: id, task: task, diff --git a/js/modules/k6/timers/timers_test.go b/js/modules/k6/timers/timers_test.go index 4d53962ea57..446a8cb229e 100644 --- a/js/modules/k6/timers/timers_test.go +++ b/js/modules/k6/timers/timers_test.go @@ -37,6 +37,17 @@ func TestSetTimeout(t *testing.T) { require.Equal(t, []string{"outside setTimeout", "in setTimeout"}, log) } +func TestSetUndefinedFunction(t *testing.T) { + t.Parallel() + + runtime := newRuntime(t) + _, err := runtime.RunOnEventLoop(` + let timers = require("k6/x/timers"); + timers.setTimeout(undefined) + `) + require.Error(t, err, "setTimeout's callback isn't a callable function") +} + func TestSetInterval(t *testing.T) { t.Parallel() runtime := newRuntime(t)