react-nativejestjsreactotron

Mocking Reactotron for Jest


I have set up Reactotron with almost default configuration:

import Reactotron from 'reactotron-react-native';
import { reactotronRedux } from 'reactotron-redux';

const reactotron = Reactotron
  .configure()
  .useReactNative()
  .use(reactotronRedux())
  .connect();

export default reactotron;

And imported it in 'index.js':

if (__DEV__) { import('./app/utils/reactotron'); }

But after this, most of Jest tests are failed with the next error:

ReferenceError: WebSocket is not defined

   8 |   .useReactNative()
   9 |   .use(reactotronRedux())
> 10 |   .connect();
     | ^
  11 | 
  12 | export default reactotron;

  at createSocket (node_modules/reactotron-react-native/dist/index.js:1:13571)
  at a.value (node_modules/reactotron-core-client/dist/index.js:1:8397)
  at Object.<anonymous> (app/utils/reactotron.js:10:1)

It looks like I need to add WebSocket or something else to global variables for tests, but should I do it for all tests or there is any way to make it once for all tests?


Solution

  • It appeared that for such cases we need to mock the reactotron-react-native package. So to solve it just put a __mocks__ folder into your root folder and add there file with the same name as package. So for this case it will be 'reactotron-react-native.js'. This file should mock all functions from the package. For me helped next one:

    const reactotron = {
      configure: () => reactotron,
      useReactNative: () => reactotron,
      use: () => reactotron,
      connect: () => reactotron,
    };
    
    module.exports = reactotron;
    

    In this case it allows chaining of the functions, so the order of calls in tests can be changed.