diff --git a/websockets/websockets.go b/websockets/websockets.go index 7b4d268..008d40f 100644 --- a/websockets/websockets.go +++ b/websockets/websockets.go @@ -784,10 +784,15 @@ func (w *webSocket) callEventListeners(eventType string) error { return nil } -func (w *webSocket) addEventListener(event string, listener func(sobek.Value) (sobek.Value, error)) { +func (w *webSocket) addEventListener(event string, handler func(sobek.Value) (sobek.Value, error)) { // TODO support options https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#parameters - if err := w.eventListeners.add(event, listener); err != nil { - w.vu.State().Logger.Warnf("can't add event listener: %s", err) + + if handler == nil { + common.Throw(w.vu.Runtime(), fmt.Errorf("handler for event type %q isn't a callable function", event)) + } + + if err := w.eventListeners.add(event, handler); err != nil { + w.vu.State().Logger.Warnf("can't add event handler: %s", err) } } diff --git a/websockets/websockets_test.go b/websockets/websockets_test.go index 0cfc3d3..be955ff 100644 --- a/websockets/websockets_test.go +++ b/websockets/websockets_test.go @@ -218,6 +218,20 @@ func TestBasic(t *testing.T) { assertSessionMetricsEmitted(t, samples, "", sr("WSBIN_URL/ws-echo"), http.StatusSwitchingProtocols, "") } +func TestAddUndefinedHandler(t *testing.T) { + t.Parallel() + ts := newTestState(t) + sr := ts.tb.Replacer.Replace + _, err := ts.runtime.RunOnEventLoop(sr(` + var ws = new WebSocket("WSBIN_URL/ws-echo") + ws.addEventListener("open", () => { + ws.close() + }) + ws.addEventListener("open", undefined) + `)) + require.ErrorContains(t, err, "handler for event type \"open\" isn't a callable function") +} + func TestBasicWithOn(t *testing.T) { t.Parallel()