首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在反应本机玩笑测试中模拟推送通知本机模块?

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

Stack Overflow用户
提问于 2017-04-01 14:17:05
回答 3查看 4.9K关注 0票数 4

在使用模块react-native-push-notification时,出现了以下错误:

代码语言:javascript
复制
 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并将此代码放入其中来模拟该模块:

代码语言:javascript
复制
const rn = require('react-native')

jest.mock('PushNotificationIOS', () => ({
  addEventListener: jest.fn(),
  requestPermissions: jest.fn(),
  then: jest.fn()
}));

module.exports = rn

现在,我有一个错误:

代码语言:javascript
复制
 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)

我怎么才能用正确的方式完全地嘲笑这个模块呢?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2017-04-01 21:13:26

我通过创建一个安装文件PushNotificationIOS来模拟模块jest/setup.js

代码语言:javascript
复制
jest.mock('PushNotificationIOS', () => {
  return {
    addEventListener: jest.fn(),
    requestPermissions: jest.fn(() => Promise.resolve()),
    getInitialNotification: jest.fn(() => Promise.resolve()),
  }
});

我已经将jest配置为通过将该行添加到packages.json来运行这个安装文件

代码语言:javascript
复制
  "jest": {
    ...
    "setupFiles": ["./jest/setup.js"],
  }
票数 8
EN

Stack Overflow用户

发布于 2017-04-01 21:08:44

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

票数 1
EN

Stack Overflow用户

发布于 2020-09-16 03:48:15

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43157979

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档