react-websocket
react-websocket copied to clipboard
npm test results in "ReferenceError: WebSocket is not defined"
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?
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!
I also get this error when using Server Side Rendering
@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
.
@mehmetkose this issue can probs be closed btw—just people misusing the library.