Document writing test expectations in chronological order in the frontend guide
Assertions should ways follow the same chronological order in which the operations executed by the test happen. A common case scenario is when a test should make assertions about a function that returns a promise and also about the results of the promise resolution:
jest
.spyOn(cluster.service, 'installApplication')
.mockRejectedValueOnce(new Error('STUBBED ERROR'));
cluster
.installApplication({ id: 'helm' })
.then(() => {
expect(cluster.store.state.applications.helm.requestStatus).toEqual(REQUEST_FAILURE);
expect(cluster.store.state.applications.helm.requestReason).toBeDefined();
})
.then(done)
.catch(done.fail);
expect(cluster.store.state.applications.helm.requestStatus).toEqual(REQUEST_SUBMITTED);
expect(cluster.store.state.applications.helm.requestReason).toEqual(null);
expect(cluster.service.installApplication).toHaveBeenCalled();
In the case above, the test makes assertions about a submitted HTTP request, toEqual(REQUEST_SUBMITTED)
, and how the function should respond when the request fails, toEqual(REQUEST_FAILURE)
. Since request failure happens after the request is submitted, the assertions are organized in the reverse order which is confusing. The reason for following this pattern is that the only way to access the promise returned by installApplication
is by calling then
immediately afterward.
To avoid this pattern, the promise can be stored in a constant and returned at the end of the test:
jest
.spyOn(cluster.service, 'installApplication')
.mockRejectedValueOnce(new Error('STUBBED ERROR'));
expect(cluster.store.state.applications.helm.requestStatus).toEqual(null);
const promise = cluster.installApplication({ id: 'helm' });
expect(cluster.store.state.applications.helm.requestStatus).toEqual(REQUEST_SUBMITTED);
expect(cluster.store.state.applications.helm.requestReason).toEqual(null);
expect(cluster.service.installApplication).toHaveBeenCalled();
return promise.then(() => {
expect(cluster.store.state.applications.helm.requestStatus).toEqual(REQUEST_FAILURE);
expect(cluster.store.state.applications.helm.requestReason).toBeDefined();
});