React Native 测试组件依赖于另一个组件

时间:2021-07-31 07:06:38

标签: react-native testing jestjs react-test-renderer

我正在使用 Jestreact-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 组件?

1 个答案:

答案 0 :(得分:1)

需要使用模拟 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
相关问题