webcontainer-core icon indicating copy to clipboard operation
webcontainer-core copied to clipboard

Support MSW version 2 to prevent this error: TypeError: Cannot read properties of undefined (reading 'on')

Open shantdashjian opened this issue 6 months ago • 1 comments

Describe the bug

When importing msw, i.e. Mock Service Worker, version 2, for example ^2.10.2, and running vitest inside a webcontainer or in StackBlitz, I get the following error:

TypeError: Cannot read properties of undefined (reading 'on')
 ❯ eval node_modules/msw/src/core/ws.ts:111:5
 ❯ _0x4067db ../../../blitz.6384d811.js:31:819992
 ❯ _0x3c6779.run ../../../blitz.6384d811.js:31:820730
 ❯ _0x2d8398 ../../../blitz.6384d811.js:31:835770
 ❯ _0x5d48ba._evaluate ../../../blitz.6384d811.js:31:836120
 ❯ _0x5a8db7 ../../../blitz.6384d811.js:31:835395
 ❯ _0x5a8db7 ../../../blitz.6384d811.js:31:835586
 ❯ _0x5a8db7 ../../../blitz.6384d811.js:31:835586

Based on the error logs above, it appears that somewhere in this file from msw a call to a function or to instantiate an object, maybe BroadcastChannel or WebSocketHandler is being blocked by webcontainers. As a result, some variable is undefined.

https://github.com/mswjs/msw/blob/main/src/core/ws.ts

Note

Using the previous version of msw, i.e. version 1, for example ^1.3.5, works just fine.

Link to the blitz that caused the error

https://stackblitz.com/edit/stackblitz-webcontainer-api-starter-5tvm1xzj

Steps to reproduce

npm run test

Expected behavior

Using msw inside webcontainers should work without an issue.

shantdashjian avatar Jun 11 '25 18:06 shantdashjian

The stack trace likely points to the .on() method call on the emitter behind the kEmittersymbol:

https://github.com/mswjs/msw/blob/13e52aa154dbd1111c7b17cc123b60aff844e55f/src/core/ws.ts#L119

This is a regular property assignment:

https://github.com/mswjs/msw/blob/13e52aa154dbd1111c7b17cc123b60aff844e55f/src/core/handlers/WebSocketHandler.ts#L48

The Emitter class itself comes from the strict-event-emitter library.

kettanaito avatar Jun 25 '25 16:06 kettanaito