Javascript 如何在React本机jest测试中模拟推送通知本机模块?

Javascript 如何在React本机jest测试中模拟推送通知本机模块?,javascript,react-native,mocking,apple-push-notifications,jestjs,Javascript,React Native,Mocking,Apple Push Notifications,Jestjs,使用模块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 NativeEven

使用模块
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)
现在,我有一个错误:

 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)
FAIL\uuuuu测试\uuuu/index.android.js
● 测试套件无法运行
TypeError:无法读取null的属性“then”
at Object..Notifications.popInitialNotification(node_modules/react native push notification/index.js:278:42)
在Object..Notifications.configure(node_modules/react native push notification/index.js:93:6)
反对。(app/utils/localPushNotification.js:4:39)
反对。(app/actions/trip.js:5:28)

如何以正确的方式完全模拟此模块?

问题在于,在抛出错误的行中,lib尝试调用react本机模块中的
getInitialNotification
,并期望返回带有某种结果的承诺。因此,您需要将此函数添加到模拟中,并让它返回一个已解决的承诺。

我通过创建一个安装文件来模拟模块
PushNotificationIOS

jest.mock('PushNotificationIOS', () => {
  return {
    addEventListener: jest.fn(),
    requestPermissions: jest.fn(() => Promise.resolve()),
    getInitialNotification: jest.fn(() => Promise.resolve()),
  }
});
我已将jest配置为通过将此行添加到
packages.json
中来运行此安装文件:

  "jest": {
    ...
    "setupFiles": ["./jest/setup.js"],
  }

您可以直接将
react native push notification ios
放入
transformignorepatterns


为什么你不模仿
react native push notification
@andreashöberle我一直在寻找模仿它的方法,我已经这么做了。感谢Andreas,我通过模仿
PushNotificationIOS
PushNotificationIOS
更改为
@react native community/push notificationios
,解决了这个问题,它工作得非常好
  "jest": {
    ...
    "setupFiles": ["./jest/setup.js"],
  }