justHelloWorld
justHelloWorld

Reputation: 6828

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?

Upvotes: 5

Views: 10234

Answers (2)

Joosep Simm
Joosep Simm

Reputation: 472

I don't understand why the previous answer (https://stackoverflow.com/a/49778196/689944) 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

Upvotes: 4

James
James

Reputation: 186

According to the docs this should do it

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

Upvotes: 3

Related Questions