React Native,Invariant Violation:Native模块不能为null。 (指向OneSignal模块)

时间:2018-06-02 17:47:02

标签: reactjs react-native jestjs onesignal

我正在使用Jest + Enzyme为使用OneSignal的本机应用程序编写测试。

这里有一个类似的问题(我认为):https://github.com/facebook/jest/issues/2208,但这个问题很老了,我已经按照那里的解决方案,但没有一个对我有效。

首先,我遇到了运行jest的错误:

home/nrion/Desktop/mobile-ui/PriceInsight_app/node_modules/react-native-onesignal/index.js:4
    import { NativeModules, NativeEventEmitter, NetInfo, Platform } from 'react-native';
    ^^^^^^

    SyntaxError: Unexpected token import

    > 1 | import OneSignal from 'react-native-onesignal';
      2 | 
      3 | export const STORE_TIMEFRAME = 'STORE_TIMEFRAME';
      4 | export const STORE_TIMEFRAMES = 'STORE_TIMEFRAMES';

      at ScriptTransformer._transformAndBuildScript (../../../../../usr/lib/node_modules/jest-cli/node_modules/jest-runtime/build/script_transformer.js:316:17)
      at Object.<anonymous> (src/actions/subscription.js:1:387)
      at Object.<anonymous> (src/reducers/subscription.js:1:402)

所以我继续将react-native-onesignal添加到package.json中:

"transformIgnorePatterns": [
      "node_modules/(?!(react-native-onesignal|react-native-login|react-native-elements)/)"
    ]

这样就解决了我的问题。但是这里出现了另一个问题:

 Invariant Violation: Native module cannot be null.

    > 1 | import OneSignal from 'react-native-onesignal';
      2 | 
      3 | export const STORE_TIMEFRAME = 'STORE_TIMEFRAME';
      4 | export const STORE_TIMEFRAMES = 'STORE_TIMEFRAMES';

      at invariant (node_modules/fbjs/lib/invariant.js:42:15)
      at new NativeEventEmitter (node_modules/react-native/Libraries/EventEmitter/NativeEventEmitter.js:37:31)
      at Object.<anonymous> (node_modules/react-native-onesignal/index.js:9:33)

我试过模仿OneSignal,但这就是我这样做时发生的事情:

 Cannot find module 'OneSignal' from 'Main.test.js'

    > 1 | import React from 'react'
      2 | import { shallow } from '../../jest-setup'
      3 | import configureStore from 'redux-mock-store'
      4 | import OneSignal from 'react-native-onesignal'

      at Resolver.resolveModule (../../../../../usr/lib/node_modules/jest-cli/node_modules/jest-resolve/build/index.js:169:17)
      at Object.<anonymous> (src/__tests__/Main.test.js:1:108)

我被这个问题困扰了好几个小时!任何见解将非常感谢,谢谢!

2 个答案:

答案 0 :(得分:1)

事实证明我的模拟是错误的。它应该是:

jest.mock('react-native-onesignal', () => ({
  addEventListener: jest.fn(),
  removeEventListener: jest.fn(),
  inFocusDisplaying: jest.fn()
}))

正如这篇帖子所指出的那样:https://github.com/facebook/jest/issues/6382#issuecomment-394104956

答案 1 :(得分:0)

我认为你缺少 babel-jest 作为依赖。 Jest默认不使用babel,因此不理解ES6导入语法。

编辑: 我还认为还有另一个问题,你需要从react-native模拟NativeEventEmitter。如果您还添加了您要测试的代码,它可能会有所帮助。