4

I recently added support for subscriptions via WebSockets to my React+Redux+ApolloGraphQL application. Since doing that I cannot run my unit tests anymore.

The problem I come up with is:

Unable to find native implementation, or alternative implementation for WebSocket!

It seems there is not an available implementation for WebSockets on the node environment where I run my tests.

There are a couple of proposed solutions in this bug report that involve using the 'ws' library for node but I cannot make them work. Either I cannot load the library properly, or I can but then the application doesn't work.

I was thinking of a way to load the library depending on the environment I'm on but:

  1. I don't know how to do that
  2. I don't know if it's the right approach.

Any suggestions?

xabitrigo
  • 1,341
  • 11
  • 24

1 Answers1

2

How are you running your tests? In my case, I'm using Jest, so I've put inside setupTests file (which is executed before running all of your tests) this code:

import WebSocket from 'ws';
Object.assign(global, {
  WebSocket,
});

This is necessary because for tests which aren't running in browser, there's no native Web Socket implementation.

Chris
  • 1,140
  • 15
  • 30