[英]How to mock Push notification native module in React native jest tests?
When using the module react-native-push-notification
, I had this error:使用模块react-native-push-notification
,出现以下错误:
FAIL __tests__/index.android.js
● Test suite failed to run
Invariant Violation: Native module cannot be null.
at invariant (node_modules/fbjs/lib/invariant.js:44:15)
at new NativeEventEmitter (node_modules/react-native/Libraries/EventEmitter/NativeEventEmitter.js:32:1)
at Object.<anonymous> (node_modules/react-native/Libraries/PushNotificationIOS/PushNotificationIOS.js:18:29)
at Object.get PushNotificationIOS [as PushNotificationIOS] (node_modules/react-native/Libraries/react-native/react-native.js:97:34)
at Object.<anonymous> (node_modules/react-native-push-notification/component/index.ios.js:10:23)
I tried to mock the module by creating __mocks__/react-native.js
and putting this code within it:我试图通过创建__mocks__/react-native.js
并将此代码放入其中来模拟模块:
const rn = require('react-native')
jest.mock('PushNotificationIOS', () => ({
addEventListener: jest.fn(),
requestPermissions: jest.fn(),
then: jest.fn()
}));
module.exports = rn
Now, I have this error:现在,我有这个错误:
FAIL __tests__/index.android.js
● Test suite failed to run
TypeError: Cannot read property 'then' of null
at Object.<anonymous>.Notifications.popInitialNotification (node_modules/react-native-push-notification/index.js:278:42)
at Object.<anonymous>.Notifications.configure (node_modules/react-native-push-notification/index.js:93:6)
at Object.<anonymous> (app/utils/localPushNotification.js:4:39)
at Object.<anonymous> (app/actions/trip.js:5:28)
How I could mock fully this module the right way?我如何以正确的方式完全模拟这个模块?
I mocked the module PushNotificationIOS
by creating a setup file jest/setup.js
:我嘲笑模块PushNotificationIOS
通过创建一个安装文件jest/setup.js
:
jest.mock('PushNotificationIOS', () => {
return {
addEventListener: jest.fn(),
requestPermissions: jest.fn(() => Promise.resolve()),
getInitialNotification: jest.fn(() => Promise.resolve()),
}
});
I've configured jest to run this setup file by adding this line into packages.json
:我通过将这一行添加到packages.json
来配置 jest 来运行这个安装文件:
"jest": {
...
"setupFiles": ["./jest/setup.js"],
}
The problem is that in the line where the error is thrown, the lib tries to call getInitialNotification
in the react-native module and expect an promise with some kind of result to be return.问题在于,在抛出错误的行中,lib 尝试调用 react-native 模块中的getInitialNotification
并期望返回具有某种结果的承诺。 So you need to add this function to the mock and let it return a resolved promise.所以你需要将这个函数添加到模拟中,让它返回一个已解决的承诺。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.