Skip to content

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

Description

@scottdickerson

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

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions