鉴于我有一个看起来很像的实现文件:
import ReactNative, { PushNotificationIOS, AsyncStorage } from 'react-native';
export function tryNotify() {
PushNotificationIOS.addEventListener('register', token => {
callback(token);
});
PushNotificationIOS.requestPermissions();
}
export function trySave(token) {
AsyncStorage.setItem('blah', token);
}
所以,如果我想编写一个可以监视以下对象的测试:
PushNotificationIOS.addEventListener
。但是,我无法弄清楚如何模拟它,因为一旦我模拟react-native
...
describe('notify()', () => {
let generator;
beforeAll(() => {
jest.mock('react-native', () => ({
PushNotificationIOS: {
addEventListener: jest.fn(),
requestPermission: jest.fn(),
},
}));
});
afterAll(() => {
jest.unmock('react-native');
});
// No tests yet!
});
...我的测试开始出现以下错误:
Invariant Violation: Navigator is deprecated and has been removed from this package. It can now be installed and imported from `react-native-deprecated-custom-components` instead of `react-native`. Learn about alternative navigation solutions at http://facebook.github.io/react-native/docs/navigation.html
我的最好的猜测是我正在干扰jest提供的内置反应本机模拟:
react-native内置的Jest预设带有一些应用于react-native存储库的默认模拟。
但是我不知道在哪里可以确认这一点。
有人有经验吗?
谢谢!
所以我有两种解决方法:
答案 0 :(得分:1)
您不能jest.mock('react-native',...
,因为react-native
对其出口进行了slightly nasty things的操作,这样就不能通过玩笑或其他方式将它们批量导入。
您需要通过直接定位模块来绕过此操作:
jest.mock('react-native/Libraries/PushNotificationIOS', () => {})