I have a save workflow in my react/redux app that requires two API calls. The second call only happens once the first call is completed successfully. The app is working great and I'm adding some automated end-to-end testing now.
I'm able to trigger the onSave
function and verify the call to saveRates
, but I'm having trouble getting the second API call to fire in my tests. Here's the code
function onSave() {
// PUT to /rates/<id>
dispatchProps.saveRates()
.then(() => {
// PUT to /apps/<id>
dispatchProps.saveApplications()
.then(() => {
// Done
});
});
}
And this is the test code. I'm using Axios for the API calls in the app and jest-mock-axios
to mock axios in my tests.
// At this point, `onSave` has been called
// This test passes
expect(mockAxios.put).toHaveBeenCalledWith(`rates/${rateId}`, { rate: { id: rateId }});
mockAxios.mockResponse({ status: 200 }, mockAxios.lastReqGet());
// This test fails with the error indicating that the expected API call was actually `PUT rates/<id>`
expect(mockAxios.put).toHaveBeenCalledWith(`app/${appId}`, { app: { id: appId, rate: rateId }});
mockAxios.mockResponse({ status: 200 }, mockAxios.lastReqGet());
It seems as though the promise from the first API call, saveRates
hasn't been resolved. The mockResponse
call resolves the promise but, using the jest debugger I can see that the call to saveApplications
never happens.
https://www.npmjs.com/package/jest-mock-axios#axiosmockresponseresponse-requestinfo
How to I tell jest to wait until the next API call happens? Do I need to return the promises from the onSave
call?
UPDATE
This works...so I suspect it can be solved with an await
somewhere.
expect(mockAxios.put).toHaveBeenCalledWith(`taxes/event/${window.storeAdminTaxEventUuid}/rates/customer`, taxRatesResponse.data.customer);
mockAxios.mockResponse({ status: 200 }, mockAxios.lastPromiseGet());
setTimeout(() => {
expect(mockAxios.put).toHaveBeenCalledWith(`taxes/event/${window.storeAdminTaxEventUuid}/application/products`, taxApplicationsResponse.data);
mockAxios.mockResponse({ status: 200 });
}, 0);