react-websocket icon indicating copy to clipboard operation
react-websocket copied to clipboard

npm test results in "ReferenceError: WebSocket is not defined"

Open scottjbarr opened this issue 7 years ago • 4 comments

I'm using react-websocket 1.1.6

This is working in development, but when running npm test on my project I see...

    ReferenceError: WebSocket is not defined

      at new Websocket (node_modules/react-websocket/build/index.js:89:16)
      at node_modules/react/lib/ReactCompositeComponent.js:294:18
      ...

The line in question is...

ws: new WebSocket(this.props.url),

Should ws be a dev dependency?

scottjbarr avatar Oct 30 '16 02:10 scottjbarr

In your test environment, are you sure WebSocket is an available API? WebSocket doesn't seem to be available in Node. Perhaps you could mock a globals.WebSocket object just for your tests. If you need complex mocking, I found this!

stevenpetryk avatar Nov 19 '16 18:11 stevenpetryk

I also get this error when using Server Side Rendering

damiangreen avatar Mar 19 '19 11:03 damiangreen

@damiangreen you cannot use WebSocket when doing Server Side Rendering, since WebSocket is not available in NodeJS. To get around this, you could do something like:

if (typeof window !== 'undefined') {
  // use WebSocket safely, only in here
}

or, if you're using React, you can place all non-SSR code inside of componentDidMount.

stevenpetryk avatar Mar 22 '19 22:03 stevenpetryk

@mehmetkose this issue can probs be closed btw—just people misusing the library.

stevenpetryk avatar Mar 22 '19 22:03 stevenpetryk