react-native-background-timer: Jest: Invariant Violation: `new NativeEventEmitter()` requires a non-null argument.
The following error will be reported if jest is not configured
FAIL __tests__/App-test.tsx
● Test suite failed to run
Invariant Violation: `new NativeEventEmitter()` requires a non-null argument.
6 | import {IconButton, TouchableRipple} from 'react-native-paper';
7 | import Ionicons from 'react-native-vector-icons/Ionicons';
> 8 | import BackgroundTimer from 'react-native-background-timer';
| ^
9 | import dayjs from 'dayjs';
10 | import relativeTime from 'dayjs/plugin/relativeTime';
11 | import 'dayjs/locale/zh-cn';
at invariant (node_modules/invariant/invariant.js:40:15)
at new NativeEventEmitter (node_modules/react-native/Libraries/EventEmitter/NativeEventEmitter.js:44:7)
at Object.<anonymous> (node_modules/react-native-background-timer/index.js:10:17)
at Object.<anonymous> (src/screens/Home.tsx:8:1)
at Object.<anonymous> (App.tsx:6:1)
at Object.<anonymous> (__tests__/App-test.tsx:7:1)
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 4.29 s, estimated 7 s
Ran all test suites.
error Command failed with exit code 1.
So maybe we should configure jest manually, like:
// jest.setup.js
jest.doMock('react-native-background-timer', () => {
return {
stopBackgroundTimer: jest.fn(),
runBackgroundTimer: jest.fn(),
};
});
This allows the unit tests to pass with flying colors
repo here: https://github.com/shensven/ReadHubn/tree/5806faf354fbd178827aff9985efe4dea906c24d
test here: https://github.com/shensven/ReadHubn/runs/3824410010?check_suite_focus=true
About this issue
- Original URL
- State: open
- Created 3 years ago
- Comments: 18
The suggested solution didn’t work for me.
While this error appears to come from
react-native-background-timer, the true culprit, if you look carefully, isreact-native/Libraries/EventEmitter/NativeEventEmitter, I solved this by adding the following to myjest.setup.js:i seem to be getting another error after doing this? i’m currently trying to mock deviceInfo module like so:
i got this error : Invariant Violation:
new NativeEventEmitter()requires a non-null argument.jest.mock('react-native/Libraries/EventEmitter/NativeEventEmitter');seems to work for me if I put it in the single test file, but not in jest.setup.json (I checked that the file is correctly loaded, and tried both with and without import { jest } from ‘@jest/globals’; I am curious as to why one works and not the other.@AdamuAbba if you have Jest installed in your project you will find this file in the root of your project. The name of the file is
jest.setup.js. If you are using VsCode, you can press Ctrl+P / Command+P and search by file name. Open that file and inside just paste the line mentioned by @princefishthrowerthese two lines in ‘jest.setup.js’ fixed the issue for the same error in react-native-device-info
maybe it’s a similar issue
please where do I find this setup file? as all the answers seem vague