Search code examples
reactjsunit-testingjestjsfetchfetch-mock

How to reset fetch-mock for each test?


I have several React tests using Jest and fetch-mock, each one of them doing some get operations, so what I initially did was:

beforeAll(){
    fetchMock.get(`*`, JSON.stringify(CORRECTRESPONSE));
}

However, in some tests I need to return wrong data as answer, something like:

test('Wrong get answer', ()=> {
   fetchMock.get('*', JSON.stringify(WRONGRESPONSE), {overwriteRoutes: true});
}));

So, since I need to reset the response for the following tests (and so return CORRECTRESPONSE, I came up with this solution:

beforeEach(){
    fetchMock.get(`*`, JSON.stringify(CORRECTRESPONSE));
}

afterEach(fetchMock.restore);

Is there anyway better to do this?


Solution

  • According to the docs this should do it

    beforeEach(() => {
      fetch.resetMocks()
    })