简体   繁体   中英

React Native Jest Expo- Native module cannot be null

I've installed jest-expo but when I run my test I get an error:

react-native/jest-preset contained different transformIgnorePatterns than expected

Invariant Violation: Native module cannot be null.

      at invariant (node_modules/invariant/invariant.js:40:15)
      at new NativeEventEmitter (node_modules/react-native/Libraries/EventEmitter/NativeEventEmitter.js:36:7)
      at new EventEmitter (node_modules/@unimodules/react-native-adapter/src/EventEmitter.ts:24:26)
      at Object.<anonymous> (node_modules/expo/src/ScreenOrientation/ScreenOrientation.ts:26:35)
      at Object.<anonymous> (node_modules/expo/src/Expo.ts:6:1)

My package.json contains:

"jest": {
    "preset": "jest-expo",
      "setupFiles": ["./jest/setup.js"],
    "transformIgnorePatterns": [
      "node_modules/(?!(jest-)?react-native|react-clone-referenced-element|@react-native-community|expo(nent)?|@expo(nent)?/.*|react-navigation|@react-navigation/.*|@unimodules/.*|unimodules|sentry-expo|native-base|@sentry/.*)"
    ]
  }

And in my setup.js file I have:

jest.mock('Linking', () => {
  return {
    addEventListener: jest.fn(),
    removeEventListener: jest.fn(),
    openURL: jest.fn(),
    canOpenURL: jest.fn(),
    getInitialURL: jest.fn(),
  }
})

My test is very simple:

import React from 'react';
import renderer from 'react-test-renderer';

import App from '../App';

describe('<App />', () => {
  it('has 1 child', () => {
expect(1).toBe(1);
  });
});

The error occurs only when I import App module. I was trying to figure out how to add ScreenOrientation module in setup.js file but I wasn't able to make it work.

Adding:

jest.mock('react-native/Libraries/EventEmitter/NativeEventEmitter.js', () => {
  const { EventEmitter } = require('events');
  return EventEmitter;
});

In setup.js file solved the problem

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM