Reputation: 646
When I run each test alone then they both succeed. But when I run them together by npm test
the second test fails:
Expected number of calls: 2
Received number of calls: 4
I have the following code: (short and cutted)
describe('checkDonations', () => {
test('it should call twice (test 1)', async () => {
const axiosSpy = jest.spyOn(axios.default, 'get')
.mockImplementation(() => {
return new Promise(resolve => {
resolve({
data: {
status: [
{
"created": "2020-04-08 21:20:17",
"timestamp": "1586373617",
"statusName": "new"
}
]
}
})
})
});
await checkDonations(null, {});
expect(axiosSpy).toHaveBeenCalledTimes(2);
})
test('it should call twice (test 2)', async () => {
const axiosSpy = jest.spyOn(axios.default, 'get')
.mockImplementation(() => {
return new Promise(resolve => {
resolve({
data: {
status: [
{
"created": "2020-04-08 21:20:17",
"timestamp": "1586373617",
"statusName": "final_success"
}
]
}
})
})
});
await checkDonations(null, {});
expect(axiosSpy).toHaveBeenCalledTimes(2);
})
})
The tests are cutted to display the issue. As you can see they are almost equal and each one has his own const of spy. Only the return value of the axiosSpy different. So I cannot place it in before each
.
Why does the second test fail when I run them by npm test
?
Upvotes: 10
Views: 13140
Reputation: 3786
Try wrapping your assertions using waitFor()
, and don't forget to use await
.
await waitFor(() => {
expect(mockBackend).toHaveBeenCalled();
});
From the docs: "Using waitFor can be useful if you have a unit test that mocks API calls and you need to wait for your mock promises to all resolve."
Upvotes: 0
Reputation: 806
If running tests individually results in everything passing, but running tests alongside a larger number of tests causes a failure, it's often fixed by giving the test a little more time to complete.
await waitFor(
() => {
let rows = getAllByTestId(distributionResultsTable, "table-row");
expect(rows).toHaveLength(101);
},
{ timeout: 2000 } // needs extra time
);
Upvotes: 0
Reputation: 4739
Delete the build-generated folder(egs: dist) and try again. It works for me.
Upvotes: 3
Reputation: 2228
You should maybe reset your mocks in a beforeEach ? I use something like the following code :
beforeEach(() => jest.resetAllMocks())
Upvotes: 14