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

How to mock Push notification native module in React native jest tests?

使用模块 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)

我试图通过创建 __mocks__/react-native.js 并将此代码放入其中来模拟模块:

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)

我怎样才能以正确的方式完全模拟这个模块?

问题在于,在抛出错误的行中,lib 尝试调用 react-native 模块中的 getInitialNotification 并期望具有某种结果的 promise 为 return .所以你需要把这个函数添加到 mock 中并让它 return 一个 resolved promise。

我通过创建安装文件 jest/setup.js:

来模拟模块 PushNotificationIOS
jest.mock('PushNotificationIOS', () => {
  return {
    addEventListener: jest.fn(),
    requestPermissions: jest.fn(() => Promise.resolve()),
    getInitialNotification: jest.fn(() => Promise.resolve()),
  }
});

我通过将此行添加到 packages.json:

来为 运行 这个设置文件配置 jest
  "jest": {
    ...
    "setupFiles": ["./jest/setup.js"],
  }

可以直接把react-native-push-notification-ios放在tranformIgnorePatterns中。