diff --git a/js/modules/k6/ws/ws.go b/js/modules/k6/ws/ws.go index 492265656fa..8eebb29830f 100644 --- a/js/modules/k6/ws/ws.go +++ b/js/modules/k6/ws/ws.go @@ -292,8 +292,11 @@ func (*WS) Connect(ctx context.Context, url string, args ...goja.Value) (*WSHTTP Tags: socket.sampleTags, Value: 1, }) - ab := rt.NewArrayBuffer(readData) - socket.handleEvent("message", rt.ToValue(string(readData)), rt.ToValue(&ab)) + socket.handleEvent("message", rt.ToValue(string(readData))) + if _, ok := socket.eventHandlers["binaryMessage"]; ok { + ab := rt.NewArrayBuffer(readData) + socket.handleEvent("binaryMessage", rt.ToValue(&ab)) + } case readErr := <-readErrChan: socket.handleEvent("error", rt.ToValue(readErr)) diff --git a/js/modules/k6/ws/ws_test.go b/js/modules/k6/ws/ws_test.go index 7c97d4aaaff..37095c655af 100644 --- a/js/modules/k6/ws/ws_test.go +++ b/js/modules/k6/ws/ws_test.go @@ -382,15 +382,21 @@ func TestSocketSendBinary(t *testing.T) { assert.NoError(t, err) _, err = rt.RunString(sr(` + var gotMsg = false, gotBinMsg = false; var res = ws.connect('WSBIN_URL/ws-echo', function(socket){ var data = new Uint8Array([104, 101, 108, 108, 111]); // 'hello' + socket.on('open', function() { socket.sendBinary(data.buffer); }) - socket.on('message', function (msg, msgBin){ + socket.on('message', function(msg) { + gotMsg = true; if (msg !== 'hello') { throw new Error('received unexpected message: ' + msg); } + }); + socket.on('binaryMessage', function(msgBin) { + gotBinMsg = true; let decText = String.fromCharCode.apply(null, new Uint8Array(msgBin)); decText = decodeURIComponent(escape(decText)); if (decText !== 'hello') { @@ -399,6 +405,12 @@ func TestSocketSendBinary(t *testing.T) { socket.close() }); }); + if (!gotMsg) { + throw new Error("the 'message' handler wasn't called") + } + if (!gotBinMsg) { + throw new Error("the 'binaryMessage' handler wasn't called") + } `)) assert.NoError(t, err) }