Skip to content

Commit

Permalink
Fix passing undefined/null handler
Browse files Browse the repository at this point in the history
  • Loading branch information
olegbespalov authored and mstoykov committed Jun 7, 2024
1 parent 7a69bb6 commit 113a951
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
11 changes: 8 additions & 3 deletions websockets/websockets.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}

Expand Down
14 changes: 14 additions & 0 deletions websockets/websockets_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down

0 comments on commit 113a951

Please sign in to comment.