How to use different return values for mocked modules in Jest

While unit testing in ReactJS, I came accross an instance where I wanted to return different values from my api call for some of the tests for the same function.

Initially I would go with something like :

jest.mock('./foor/bar', ({
fetchData : jest.fn()
  .mockResolvedValueOnce({ ... my response for the first test })
  .mockResolvedValue({ ... response for the rest })
}))

This works fine but is dependent on the order of my test, so in case where your working with a group and your test could be updated later on by you or someone else, it’s possible to miss this test and could end up taking some of your dev time.

What I found while searching online was to implement something like this (I wasn’t aware this was possible before) :

//import your module/library in your test
import BarApi from './foo/bar';

// then create a generic mock of the function
jest.mock('./foo/bar/', ({
  fetchData: jest.fn()
}))

// inside your test you can now do something like
BarApi.fetchData.mockReturnValue({ specific value for this test })

// on another test you could implement a completely different response
BarApi.fetchData.mockReturnValue({ different response })

I hope this helps you save some time researching for a solution.

Cheers!

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *