typescriptjestjs

jest describe suite fails but running test independently succeeds


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 ?


Solution

  • You should maybe reset your mocks in a beforeEach ? I use something like the following code :

    beforeEach(() => jest.resetAllMocks())