异步测试-Mocha和Chai-确保正在调用done()回调 [英] Async Tests - Mocha and Chai - Ensure the done() callback is being called
问题描述
我正在尝试测试我的容器组件方法.我的容器有一个异步方法,可以加载所有建议并设置为状态.例子.
I'm trying test my container component methods. My container had a async method that load all proposals and set in the state. Example.:
loadProposal(proposalId) {
return axios
.get("http://localhost:9292/api/proposal_drafts/1.json")
.then(response => {
this.setState({
proposal: Immutable.fromJS(response.data)
})
})
}
因此,为了测试此方法,我获取了组件实例并调用了该方法(对api url进行了模拟).
So, to test this method i get the component instance and call the method (the api url is mocked).
it("sets proposal in the state", (done) => {
const wrapper = shallow(<Container/>)
loadProposalRequest(1)
wrapper.instance().loadProposal(1).then(() => {
chai.expect(wrapper.state().proposal).to.be(Map)
done()
})
})
但是我从控制台收到此错误:
But i get this error from console:
错误:超时超过2000毫秒.确保已完成done()回调 在此测试中被调用.
Error: timeout of 2000ms exceeded. Ensure the done() callback is being called in this test.
操作:如果我将console.log(wrapper.state())放在then()里面.日志正确显示了我的状态.
Ops: If i put a console.log(wrapper.state()) inside then() . The log shows my state correctly.
推荐答案
如果chai.expect()
引发错误(我认为这是正在发生的事情),则会发生两件事:
If chai.expect()
throws an error (which I think is what's happening), two things will happen:
-
由于抛出错误,
-
done
不会被调用; - 不会捕获错误,因为没有其他错误处理.
done
won't get called, because of the thrown error;- the error won't get caught, because there's not additional error handling.
您应该使用Mocha的Promise支持来消除这两个问题:
You should use Mocha's promise support instead to remove both issues:
it("sets proposal in the state", () => {
const wrapper = shallow(<Container/>)
loadProposalRequest(1)
return wrapper.instance().loadProposal(1).then(() => {
chai.expect(wrapper.state().proposal).to.be(Map)
})
})
这篇关于异步测试-Mocha和Chai-确保正在调用done()回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!