我正在使用Jest
和react-test-renderer
测试我的组件。当我仅从react-native
模块导入测试纯组件时,一切正常。例如,当我测试以下组件时:
import React from 'react';
import {Text, View} from 'react-native';
export default class Splash extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<View testID={'splash-test-1'}>
<Text>This is Splash Screen</Text>
</View>
);
}
}
使用以下代码,测试将通过,没有问题:
it('Splash Screen', () => {
const screen= renderer.create(<Splash/>).root;
expect(screen.findByProps({testID: 'splash-test-1'}).children.length).toBe(1);
})
但是当我在我的代码之上添加任何模块时,比如 RBFetchblob(例如import RNFetchBlob from "rn-fetch-blob";
),我得到一个错误。例如在导入 RNFetchblob 时,会出现以下错误:
● Test suite failed to run
D:\Projects\MyProject\node_modules\rn-fetch-blob\index.js:5
import {
^^^^^^
SyntaxError: Cannot use import statement outside a module
......
我的问题是如何在具有许多依赖项的真实项目中测试 React Native 组件?
需要使用模拟https://jestjs.io/docs/manual-mocks#mocking-node-modules
对于您的示例,在根项目中需要创建__mocks__
文件夹并放置rn-fetch-blob
带有代码的文件:
jest.mock('rn-fetch-blob', () => {
return () => ({
fs: jest.fn(),
config: jest.fn(),
DocumentDir: jest.fn(),
});
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句