测试componentDidMount
中的异步调用是否设置React组件的状态的最佳方式是什么?对于上下文,我用于测试的库是Mocha
,Chai
,Enzyme
和Sinon
。如何在componentDidMount中测试异步调用,以设置React组件的状态
下面是一个例子代码:
/*
* assume a record looks like this:
* { id: number, name: string, utility: number }
*/
// asyncComponent.js
class AsyncComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
records: []
};
}
componentDidMount() {
// assume that I'm using a library like `superagent` to make ajax calls that returns Promises
request.get('/some/url/that/returns/my/data').then((data) => {
this.setState({
records: data.records
});
});
}
render() {
return (
<div className="async_component">
{ this._renderList() }
</div>
);
}
_renderList() {
return this.state.records.map((record) => {
return (
<div className="record">
<p>{ record.name }</p>
<p>{ record.utility }</p>
</div>
);
});
}
}
// asyncComponentTests.js
describe("Async Component Tests",() => {
it("should render correctly after setState in componentDidMount executes",() => {
// I'm thinking of using a library like `nock` to mock the http request
nock("http://some.url.com")
.get("/some/url/that/returns/my/data")
.reply(200, {
data: [
{ id: 1, name: "willson", utility: 88 },
{ id: 2, name: "jeffrey", utility: 102 }
]
});
const wrapper = mount(<AsyncComponent />);
// NOW WHAT? This is where I'm stuck.
});
});
难道你不只是断言你的状态更新正确吗?我并不熟悉使用Enzyme并且不使用'shallow()'api,但对于浅渲染组件,您可以假定状态更新是同步的。 –
我的问题更侧重于这个异步部分 - 如果我最初在渲染之后声明状态,那么'records'将是空数组。相反,我希望在'componentDidMount'中的承诺将状态设置为非空数组之后进行断言。 – wmock
实际上,最好的做法是将该功能移出组件,以便可以单独进行测试,并且可以对其进行嘲讽以测试组件。但是你总是可以使用setTimeout。你可以控制诺克,所以你可以肯定答案会花多长时间。 – aray12