【问题标题】:React Native testing components with depends on another componentsReact Native 测试组件依赖于另一个组件
【发布时间】:2021-07-31 17:25:13
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

    需要使用 mocks 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(),
      });
    });
    

    【讨论】:

    • 感谢您的回复。使用上面的代码,解决了 rn-fetch-blob 错误,但现在我收到另一个错误:TypeError: Cannot read property 'BaseComponent' of undefined。 BaseComponent 是我自己的组件,它扩展了 React.Component 包括一些全局函数。我必须为自己的组件执行此操作吗?能说详细一点吗?
    • 您编写单元测试,因此您需要模拟所有全局和副作用函数。例如,您可以模拟您的组件jest.mock(() =&gt; 'BaseComponent')。关于 mocking React 组件的详细信息thoughtbot.com/blog/mocking-react-components-with-jest
    猜你喜欢
    • 2021-12-09
    • 2020-01-11
    • 2020-10-18
    • 2021-08-08
    • 2017-10-31
    • 1970-01-01
    • 2019-10-23
    • 2023-03-04
    • 1970-01-01
    相关资源
    最近更新 更多