我有一个父组件,它呈现一个子组件列表,但它基于我从API调用中获得的结果,设置父组件的状态,并使用this.state
呈现子组件。我现在遇到的问题是,由于setState
是一个异步函数,当父组件mounted
使用Enzyme时,setState
尚未完成,因此子组件在DOM中不存在。我只是想知道在这种情况下测试子组件是否存在的正确方法是什么?
任何帮助将不胜感激!
ParentComponent.js
componentDidMount() {
someAsyncAPICall().then(status => {
this.setState({status: status});
});
}
render() {
return (
{this.state.status.map((object, rowIndex) =>
<ChildComponent key={object.id}
...
/>
)}
);
}
父母的摩卡单元测试
import React from 'react';
import {expect} from 'chai';
import {mount} from 'enzyme';
import fetchMock from 'fetch-mock';
...
describe('ParentComponent', () => {
const baseURL = "http://localhost:8000";
const status = [{
...
}];
before(() => {
fetchMock.get(`${baseURL}/api`, status);
});
after(() => {
fetchMock.reset();
fetchMock.restore();
});
it('contains the correct number of components', (done) => {
const wrapper = mount(<ParentComponent />);
//This is not working - the length of ChildComponent is always 0
expect(wrapper.find(ChildComponent).length).to.equal(status.length);
});
});