如何在React Native Jest测试中模拟Push Notification Native模块? [英] How to mock Push notification native module in React native jest tests?
本文介绍了如何在React Native Jest测试中模拟Push Notification Native模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用模块react-native-push-notification
时,出现此错误:
When using the module react-native-push-notification
, I had this error:
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)
我尝试通过创建__mocks__/react-native.js
并将此代码放入其中来模拟该模块:
I tried to mock the module by creating __mocks__/react-native.js
and putting this code within it:
const rn = require('react-native')
jest.mock('PushNotificationIOS', () => ({
addEventListener: jest.fn(),
requestPermissions: jest.fn(),
then: jest.fn()
}));
module.exports = rn
现在,我遇到此错误:
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?
推荐答案
我通过创建安装文件jest/setup.js
来模拟模块PushNotificationIOS
:
I mocked the module PushNotificationIOS
by creating a setup file jest/setup.js
:
jest.mock('PushNotificationIOS', () => {
return {
addEventListener: jest.fn(),
requestPermissions: jest.fn(() => Promise.resolve()),
getInitialNotification: jest.fn(() => Promise.resolve()),
}
});
我已通过将以下行添加到packages.json
中来配置玩笑来运行此安装文件:
I've configured jest to run this setup file by adding this line into packages.json
:
"jest": {
...
"setupFiles": ["./jest/setup.js"],
}
这篇关于如何在React Native Jest测试中模拟Push Notification Native模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文