When I assert the number of time the mocked function been called the imported mocked function always return the bined 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();
});
});
});
When I assert the number of time the mocked function been called the imported mocked function always return the bined 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();
});
});
});
Share
Improve this question
edited Nov 2, 2018 at 18:56
skyboyer
23.8k7 gold badges62 silver badges71 bronze badges
asked Oct 8, 2018 at 3:26
XYZXYZ
27.5k15 gold badges94 silver badges167 bronze badges
1 Answer
Reset to default 6mockFn.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();
});