如何在React Native Jest测试中模拟推送通知本地模块?

4
当使用模块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.jsTest 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)

我该如何正确地模拟这个模块呢?

为什么你不模拟react-native-push-notification - Andreas Köberle
@AndreasKöberle 我在寻找模拟的方法,我已经成功了。 - Assem
3个回答

8

我通过创建一个设置文件 jest/setup.js 来模拟模块 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"],
  }

5
PushNotificationIOS 更改为 @react-native-community/push-notification-ios,它就可以完美运行。 - Kasra

1
问题在于,错误所在的行中,该库尝试调用 react-native 模块中的 getInitialNotification 函数,并期望返回某种结果的 promise。因此,您需要将此函数添加到模拟中,并让它返回一个已解决的 promise。

谢谢Andreas,我通过模拟“PushNotificationIOS”解决了问题。 - Assem

0

您可以直接将react-native-push-notification-ios放入tranformIgnorePatterns中。

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接