Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

react-use-websocket is not compatible with MSWJS #263

Open
scottdickerson opened this issue Feb 27, 2025 · 0 comments
Open

react-use-websocket is not compatible with MSWJS #263

scottdickerson opened this issue Feb 27, 2025 · 0 comments

Comments

@scottdickerson
Copy link

To see the error:

  • add mswjs to a React project using"react-use-websocket": "4.10.0",.
  • startup the msw client side service worker on server startup with
import { setupWorker } from 'msw/browser';

const worker = setupWorker(...handlers);
  await worker.start();
  return worker;
  • connect to the websocket with useWebsocket and invoke sendJsonMessage
const { sendJsonMessage } = useWebSocket<MessageResponseType>(
      webSocketUrl
    );

In the react-use-websocket util.ts code, before it sends the message, it calls assertIsWebSocket. This has this line to check the class:

  if (!skip && webSocketInstance instanceof WebSocket === false) throw new Error('');

Unfortunately when msw starts it's worker it intercepts WebSocket instantiations and when a WebSocket is created it instead makes an instance of the class named WebSocketOverride so this check fails, throws and error and breaks sendJsonMessage

util.ts:9 Uncaught Error
    at assertIsWebSocket (util.ts:9:74)
    at use-websocket.ts:61:7
    at Object.sendJsonMessage (use-websocket.ts:69:5)
    at sendJsonMessage (hooks.ts:182:24)
    at handleBidSubmission (LotBiddingModal.tsx:111:7)
    at onSubmit (LotBiddingModal.tsx:163:13)
    at submitHandler (chunk-SYFQ2XB5.mjs:7314:19)
    at HTMLUnknownElement.callCallback2 (react-dom.development.js:4164:14)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:4213:16)
    at invokeGuardedCallback (react-dom.development.js:4277:31)
assertIsWebSocket @ util.ts:9
(anonymous) @ use-websocket.ts:61
(anonymous) @ use-websocket.ts:69
sendJsonMessage @ hooks.ts:182

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant