測試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