From 5819f62d3ea9f59a9b7b1524c01f50c8a4c92e64 Mon Sep 17 00:00:00 2001 From: Oleg Bespalov Date: Thu, 6 Jun 2024 12:23:16 +0200 Subject: [PATCH] Handling undefined function in timers --- js/modules/k6/timers/timers.go | 16 +++++++++++----- js/modules/k6/timers/timers_test.go | 11 +++++++++++ 2 files changed, 22 insertions(+), 5 deletions(-) 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)