Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot find module 'EventEmitter' from 'setupJest.js' with React Native 0.61.0

I have the following setupJest.js file that I use before running my React Native tests.

// Required to correctly polyfill React-Native

import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

configure({ adapter: new Adapter() });

global.XMLHttpRequest = jest.fn();
global.fetch = jest.fn();

if (typeof window !== 'object') {
  global.window = global;
  global.window.navigator = {};
}

const EventEmitter = require('EventEmitter');
const RCTDeviceEventEmitter = require('RCTDeviceEventEmitter');

class NativeEventEmitter extends EventEmitter {
  constructor() {
    super(RCTDeviceEventEmitter.sharedSubscriber);
  }
}

Here's an example test:

/**
 * @format
 */

import 'react-native';
import React from 'react';
import App from '../App';

// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';

jest.mock('NativeEventEmitter');

it('renders correctly', () => {
  renderer.create(<App />);
});

This worked fine with React Native 0.60.x. However, with React Native 0.61.0, I get the following error:

Cannot find module 'EventEmitter' from 'setupJest.js'

If I change my imports to match where the files are in node_modules, I don't get much further.

const EventEmitter = require('react-native/Libraries/vendor/emitter/EventEmitter');
const RCTDeviceEventEmitter = require('react-native/Libraries/EventEmitter/RCTDeviceEventEmitter');

Any idea how to update my code so it works with React Native 0.61.0?

Cannot find module 'NativeEventEmitter' from 'App-test.js'

  10 | import renderer from 'react-test-renderer';
  11 | 
> 12 | jest.mock('NativeEventEmitter');
     | ^
  13 | 
  14 | it('renders correctly', () => {
  15 |   renderer.create(<App />);

  at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:259:17)
  at Object.<anonymous> (tests/App-test.js:12:1)

You can reproduce this problem by cloning the following repo and running its tests:

git clone -b react-native-61 https://github.com/mraible/samples-js-react-native.git
cd samples-js-react-native/browser-sign-in
npm i
npm test
like image 949
Matt Raible Avatar asked Dec 14 '22 10:12

Matt Raible


1 Answers

RN library has mock implementation for the NativeEventEmitter class. Just remove the following code from setupJest.js:

const EventEmitter = require('EventEmitter');
const RCTDeviceEventEmitter = require('RCTDeviceEventEmitter');

class NativeEventEmitter extends EventEmitter {
  constructor() {
    super(RCTDeviceEventEmitter.sharedSubscriber);
  }
}

And setup mock in your test file:

jest.mock(
  '../node_modules/react-native/Libraries/EventEmitter/NativeEventEmitter',
);

Don't forget to remove:

jest.mock('NativeEventEmitter');
like image 156
Ildar Abdullin Avatar answered Jan 01 '23 13:01

Ildar Abdullin