我正在从组件的componentDidMount函数向我的API http://localhost:3001/api/cards
发出GET请求,因此只有在第一次呈现组件后才会发出api请求(正如反应官方指南所建议的那样) )。
此API设置数组data
的状态。在render函数中,我调用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);
});
}
有没有我不理解的概念?我应该如何理想地测试这种异步加载组件?我怎样才能更好地设计它们以便于测试?任何帮助将不胜感激。感谢
答案 0 :(得分: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);
});