我正在使用Jest+Enzyme为一个使用OneSignal
的React Native应用编写测试。
这里可能有一个类似的问题(我想):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)
这个问题困扰了我好几个小时!希望能得到一些指导。