如何在componentDidMount中测试由异步调用创建的组件?

Ayu*_*ush 4 javascript unit-testing reactjs jestjs enzyme

我正在http://localhost:3001/api/cards从组件的componentDidMount函数向我的API发出GET请求,因此只有在第一次呈现组件之后才会发出api请求(如反应官方指南所示).

此API设置数组的状态data.在render函数中,我调用data.mapfunction来从这个数组中渲染多个组件.我该如何测试是否已呈现所需数量的组件?

我的组件:

//CardGrid.js

import React from 'react';
import { Card, Col, Row } from 'antd';
import 'antd/dist/antd.css';

import { parseJSON } from './commonfunction';
import './CardGrid.css';

export default class extends React.Component {
    constructor()
    {
        super();
        this.state = {
            data: {},
        };
    }

    fetchData = async () => {
        try
        {
            const data = await parseJSON(await fetch('http://localhost:3001/api/cards'));
            console.log('data');
            console.log(data);
            this.setState({ data });
        }
        catch (e)
        {
            console.log('error is: ');
            console.log(e);
        }
    }

    componentDidMount() {
        this.fetchData();
    }

    render() {
        return (
            <div style={{ background: '#ECECEC', padding: '30px' }}>
                <Row gutter={16}>
                    {Object.keys(this.state.data).map((title) => {
                        return (<Col span="6" key={title}>
                            <Card title={title} bodyStyle={{
                                'fontSize': '6em',
                            }}>{this.state.data[title]}</Card>
                        </Col>);
                    })}
                </Row>
            </div>
        );
    }
};
Run Code Online (Sandbox Code Playgroud)

现在我想检查是否有尽可能多的Card组件被我的API指定.

我试过这个,首先模拟fetch函数返回1个元素.然后我使用酶的完整DOM渲染和mount上面的组件,并期望它包含1个元素.

测试用例:

// It fails
import React from 'react';
import { Card } from 'antd';
import { mount } from 'enzyme';
import CardGrid from './CardGrid';

it('renders 1 Card element', () => {
    fetch = jest.fn().mockImplementation(() =>
        Promise.resolve(mockResponse(200, null, '{"id":"1234"}')));
    const wrapper = mount(<CardGrid />);
    expect(fetch).toBeCalled();
    expect(wrapper.find(CardGrid).length).toEqual(1);
    expect(wrapper.find(Card).length).toEqual(1);
});
Run Code Online (Sandbox Code Playgroud)

所有测试都通过,但它找不到Card元素.甚至调用fetch mock函数也是如此.它在我尝试查找Card组件之前放入setTimeout函数时失败.

//It succeeds
import React from 'react';
import { Card } from 'antd';
import { mount } from 'enzyme';
import sinon from 'sinon';
import CardGrid from './CardGrid';
it('renders 1 Card elements', async () => {
    fetch = jest.fn().mockImplementation(() =>
        Promise.resolve(mockResponse(200, null, '{"id":"1234"}')));
    const wrapper = mount(<CardGrid />);
    expect(fetch).toBeCalled();
    expect(wrapper.find(CardGrid).length).toEqual(1);
    await setTimeoutP();
    expect(wrapper.find(Card).length).toEqual(1);

});

function setTimeoutP () {
    return new Promise(function (resolve, reject) {
        setTimeout(() => {
            console.log('111111111');
            resolve();
        }, 2000);
    });
}
Run Code Online (Sandbox Code Playgroud)

有没有我无法理解的概念?我应该如何理想地测试这种异步加载组件?我怎样才能更好地设计它们以便于测试?任何帮助将不胜感激.谢谢

And*_*rle 6

你必须等待你的获取结果的解决承诺和来自的承诺parseJSON.因此我们需要模拟parseJSON并让它返回一个已解决的承诺.请注意,路径需要相对于测试文件.

import {parseJSON} from './commonfunction'

jest.mock('./commonfunction', () => {parseJSON: jest.fn()}) //this will replace parseJSON in the module by a spy were we can later on return a resolved promise with


it('renders 1 Card elements', async () => {
    const result = Promise.resolve(mockResponse(200, null, '{"id":"1234"}')) 
    parsedResult = Promise.resolve({"id":"1234"})
    parseJSON.mockImplementation(()=>parsedResult)
    fetch = jest.fn(() => result)
    const wrapper = mount(<CardGrid />);
    await result;
    await parsedResult;

    expect(fetch).toBeCalled();
    expect(wrapper.find(CardGrid).length).toEqual(1);
    expect(wrapper.find(Card).length).toEqual(1);
});
Run Code Online (Sandbox Code Playgroud)