如何解决React Native 测试组件依赖于另一个组件
我正在使用 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
对于您的示例,在根项目中需要创建 >>> df
x
0 DIV.CDN
1 DIV.XYN
2 VIM.NGN
3 VIM.AHY
>>> df['x'].str[-1]
0 N
1 N
2 N
3 Y
Name: x,dtype: object
文件夹并使用代码放置文件 __mocks__
:
rn-fetch-blob
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。