XYZ
XYZ

Reputation: 27387

How to make Jest mocked function toHaveBeenCalledTimes has a fresh count for each test suite?

When I assert the number of time the mocked function been called the imported mocked function always return the combined number of invocations.

For example, the first test suite has a function called the mocked function import { get } from 'axios' once and the expected toHaveBeenCalledTimes is 1. However, the second test suite, the function called get again and toHaveBeenCalledTimes is 2 instead of 1.

How to make the mocked function toHaveBeenCalledTimes return a refresh count for each test suit?

describe('fetchAData', () => {
    it('should return the right A data response', (done) => {
        const sampleResponse = { data: dataASample };

        get.mockImplementationOnce(() => {
            return Promise.resolve(sampleResponse);
        });

        fetchAData().then(() => {
            expect(get).toHaveBeenCalledTimes(1);

            done();
        });
    });
});

describe('fetchBData', () => {
    it('should return the right B data response', (done) => {
        const sampleResponse = { data: dataBSample };

        get.mockImplementationOnce(() => {
            return Promise.resolve(sampleResponse);
        });

        fetchBData().then(() => {
            expect(get).toHaveBeenCalledTimes(1); // -> Return `2`
            done();
        });
    });
});

Upvotes: 3

Views: 4175

Answers (1)

XYZ
XYZ

Reputation: 27387

mockFn.mockReset() just did the trick, https://jestjs.io/docs/en/mock-function-api#mockfnmockreset

Does everything that mockFn.mockClear() does, and also removes any mocked return values or implementations.

beforeEach(() => {
    get.mockReset();
});

Upvotes: 6

Related Questions