How to reset fetch-mock for each test?
Asked Answered
E

2

5

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?

Episcopal answered 1/3, 2018 at 15:48 Comment(0)
S
3

According to the docs this should do it

beforeEach(() => {
  fetch.resetMocks()
})
Sensuality answered 11/4, 2018 at 14:48 Comment(1)
Please cite your sourcePerpetuity
P
4

I don't understand why the previous answer (https://mcmap.net/q/2002918/-how-to-reset-fetch-mock-for-each-test) was set as correct. Cleanup up after tests by afterEach(fetchMock.restore) is a very good way.

That's also what is described in the fetch-mock documentation: http://www.wheresrhys.co.uk/fetch-mock/#api-lifecyclerestore_reset

Polynices answered 8/7, 2019 at 13:22 Comment(0)
S
3

According to the docs this should do it

beforeEach(() => {
  fetch.resetMocks()
})
Sensuality answered 11/4, 2018 at 14:48 Comment(1)
Please cite your sourcePerpetuity

© 2022 - 2024 — McMap. All rights reserved.