When using the module react-native-push-notification
, I had this error:
JavaScript
x
11
11
1
FAIL __tests__/index.android.js
2
● Test suite failed to run
3
4
Invariant Violation: Native module cannot be null.
5
6
at invariant (node_modules/fbjs/lib/invariant.js:44:15)
7
at new NativeEventEmitter (node_modules/react-native/Libraries/EventEmitter/NativeEventEmitter.js:32:1)
8
at Object.<anonymous> (node_modules/react-native/Libraries/PushNotificationIOS/PushNotificationIOS.js:18:29)
9
at Object.get PushNotificationIOS [as PushNotificationIOS] (node_modules/react-native/Libraries/react-native/react-native.js:97:34)
10
at Object.<anonymous> (node_modules/react-native-push-notification/component/index.ios.js:10:23)
11
I tried to mock the module by creating __mocks__/react-native.js
and putting this code within it:
JavaScript
1
10
10
1
const rn = require('react-native')
2
3
jest.mock('PushNotificationIOS', () => ({
4
addEventListener: jest.fn(),
5
requestPermissions: jest.fn(),
6
then: jest.fn()
7
}));
8
9
module.exports = rn
10
Now, I have this error:
JavaScript
1
10
10
1
FAIL __tests__/index.android.js
2
● Test suite failed to run
3
4
TypeError: Cannot read property 'then' of null
5
6
at Object.<anonymous>.Notifications.popInitialNotification (node_modules/react-native-push-notification/index.js:278:42)
7
at Object.<anonymous>.Notifications.configure (node_modules/react-native-push-notification/index.js:93:6)
8
at Object.<anonymous> (app/utils/localPushNotification.js:4:39)
9
at Object.<anonymous> (app/actions/trip.js:5:28)
10
How I could mock fully this module the right way?
Advertisement
Answer
I mocked the module PushNotificationIOS
by creating a setup file jest/setup.js
:
JavaScript
1
8
1
jest.mock('PushNotificationIOS', () => {
2
return {
3
addEventListener: jest.fn(),
4
requestPermissions: jest.fn(() => Promise.resolve()),
5
getInitialNotification: jest.fn(() => Promise.resolve()),
6
}
7
});
8
I’ve configured jest to run this setup file by adding this line into packages.json
:
JavaScript
1
5
1
"jest": {
2
3
"setupFiles": ["./jest/setup.js"],
4
}
5