首页 文章

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

提问于
浏览
4

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

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

我的组件:

//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>
        );
    }
};

现在我想检查是否有尽可能多的 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);
});

所有测试都通过,但它找不到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);
    });
}

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

1 回答

  • 5

    您必须wait获取已获取结果的承诺以及来自 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);
    });
    

相关问题