jest-fetch-mock
jest-fetch-mock copied to clipboard
fetch.resetMocks not resetting fetch
So as the title implies fetch.mockResets() isn't resetting the the fetch.
here is my full test.js:
import Worker from '../statistics-worker/worker';
jest.mock("../statistics-worker/worker");
const workerInitProps = {
interactionId: '123',
interactionSubmissionUrl: 'submission',
fetchUrl: 'fetch'
};
const statService = Statistic.getNewInstance(new Worker(workerInitProps));
describe('Statistic serivce ', () => {
beforeEach(() => {
fetch.resetMocks();
});
it('Should init worker', () => {
expect(statService).toBeInstanceOf(Statistic);
});
it('should fetch statistics', () => {
fetch.mockResponseOnce(
JSON.stringify({
payload: {
statistics: {
1: 10,
2: 11
},
count: 10,
finalResults: []
}
})
);
statService
.fetchStatistics()
.then(res => {
expect(res).toEqual({
statistics: {
1: {
options: 10,
totalVotes: 0
},
2: {
options: 11,
totalVotes: 0
}
},
count: 10,
finalResults: []
});
})
.catch(err => {
expect(err).toBeFalsy();
});
});
it('should deadlock fetch statistics', () => {
fetch.mockRejectOnce(new Error('fake error message'));
const statistics = Statistic.getNewInstance(new Worker(workerInitProps));
statService
.fetchStatistics()
.then(res => {
console.log(res);
expect(res).toEqual({
count: 0,
statistics: {},
dead: true
});
})
.catch(err => {
expect(err).toBeFalsy();
});
});
});
The result i get is:
Expected value to equal:
{"count": 0, "dead": true, "statistics": {}}
Received:
{"count": 10, "finalResults": [], "statistics": {"1": {"options": 10, "totalVotes": 0}, "2": {"options": 11, "totalVotes": 0}}}
Did you manage to fix this? I finally had some time recently to look through the example. I'm a bit confused why it's going into the .then when it should just hit the catch if you're rejecting.
Struggling with this here as well, always returns the value provided in the first test with mockOnce(...) even for one of the tests where I use fetchMock.mockRejectOnce()
Looks like the request URL needs to be different to get different response. I find this quite confusing.
Setting a mock response in one test should not be returned in another test.
Even resetMocks() has no effect.
Has anyone been able to work this one out? Running into this issue myself. The mocked response is always from the test run previously. resetMocks doesn't seem to do anything.
For anyone stumbling upon this: Save yourself the hours of troubleshooting and just use msw: https://mswjs.io/docs/integrations/node/
resetMocks() in this lib definitely doesn't work which makes it useless for anyone developing real software tests.