我正在使用带有sinon的react应用程序进行测试,这是一些背景知识
容器<UpgradeApp />
class UpgradeApp extends Component {
...
onFileUpload() {
this.updateProgressBar(true); // I can only get this spy call detected
return fetch(
`/api/v1/upload-files/`,
{
credentials: 'include',
method: 'POST',
body: formObj,
headers: {'X-CSRFToken': this.props.csrf},
}
)
.then((res) => {
if (res.status >= 400) {
// error handling here...
throw new Error(`Bad server responses, status code: ${res.status}`);
}
return res.json();
})
.then((ans) => {
if (ans.success) {
this.setState({
...this.state,
dialog: {
...this.state.dialog,
submitFn: () => {
return restfulApiCall(
this.props.csrf,
'upgrade',
).then((res) => {
if (res.status >= 400) {
// error handling here...
throw new Error(`Bad server responses, status code: ${res.status}`);
}
}).catch((err) => {
console.log('in catch');
this.updateProgressBar(false); // Want to test whether this fn is called
});
}
}
}
}
});
}
...
}
测试upgrade.spec.js
测试是检查功能this.updateProgressBar
是否正在执行,但是我只在第一次调用中得到被监视的间谍,而在第二次调用中却没有。
从控制台日志消息的顺序来看,我可以看到in catch
在in then
之前,因此可以确定在测试用例评估该功能之前是否正在执行catch块,是否有关于这方面的线索?谢谢
...
const spyUpdateProgressBar = spy(upgradeAppInstance, 'updateProgressBar');
it('should hide the progress bar when upgrade is failed', function (done) {
fetchMock.post(regUploadExp, mockOkUploadHttpResponse);
fetchMock.post(regUpgradeExp, mockHttpUpgradeResponse);
upgradeAppInstance.onFileUpload().then(() => {
wrapper.update();
expect(wrapper.find(ADialog).at(0).props().open).to.equal(true);
const mockButtons2 = wrapper.find(ADialog).dive().at(0).find(Button);
expect(spyUpdateProgressBar.calledOnce).to.equal(true); // This test is passed as expected
spyUpdateProgressBar.resetHistory();
// simulate upgrade process
mockButtons2.at(1).simulate('click');
console.log('in then');
});
setImmediate(() => {
console.log(spyUpdateProgressBar.callCount);
expect(spyUpdateProgressBar.calledOnce).to.equal(true); // failed in this expect, expecting true but get false
done();
});
});