【问题标题】:How to mock Push notification native module in React native jest tests?如何在 React 本机笑话测试中模拟推送通知本机模块?
【发布时间】:2017-08-26 17:55:01
【问题描述】:

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

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

【问题讨论】:

  • 你为什么不嘲笑react-native-push-notification
  • @AndreasKöberle 我一直在寻找模拟它的方法,我已经做到了。

标签: javascript react-native mocking apple-push-notifications jestjs


【解决方案1】:

你可以直接把react-native-push-notification-ios放到tranformIgnorePatterns里面。

【讨论】:

    【解决方案2】:

    我通过创建一个设置文件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"],
      }
    

    【讨论】:

    • PushNotificationIOS 更改为 @react-native-community/push-notification-ios 并且效果很好
    【解决方案3】:

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

    【讨论】:

    • 谢谢安德烈亚斯,我通过嘲笑PushNotificationIOS解决了
    猜你喜欢
    • 2015-10-30
    • 1970-01-01
    • 2019-04-13
    • 2020-09-03
    • 2019-08-03
    • 2018-07-15
    • 2021-02-10
    • 2017-02-13
    • 2018-09-18
    相关资源
    最近更新 更多