I am testing with a react application with sinon, here is some backgrounds
- A file uploader is created for user to upload the file to server, after the upload has completed, a dialog box will pop out showing the details of the uploaded files
Container <FWUpgradeApp />
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
});
}
}
}
}
});
}
...
}
Test upgrade.spec.js
The test is to check whether the function this.updateProgressBar
is being executed, but I only get the called spyed in first call, but not the second one.
From the order of console log message, I can see in catch
is before in then
, so it is pretty sure that the catch block is being executed before the test case evaluating the function, is there any clues regarding on this? Thank you
...
const spyUpdateProgressBar = spy(fwupgradeAppInstance, 'updateProgressBar');
it('should hide the progress bar when upgrade is failed', function (done) {
fetchMock.post(regUploadExp, mockOkUploadHttpResponse);
fetchMock.post(regUpgradeExp, mockHttpUpgradeResponse);
fwupgradeAppInstance.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();
});
});
Aucun commentaire:
Enregistrer un commentaire