How to mock a module that exports a factory function with Jest

Mattia Richetto
1 min readDec 9, 2018

--

If you have a module that exports a factory function and you want to mock one or more methods of the object returned by that function, this may be the solution you are looking for:

https://gist.github.com/mattiaerre/da3fe3f01504bb5e2e481a16dafb96f4

This is where the magic happens:

jest.mock('./makeMenusClient', () => {  const mockMenusClient = { getMenus: jest.fn() };  return jest.fn(() => mockMenusClient);});

You need to mock your module so that the constructor function should return the object you would like to mock, wrapped around a jest.fn(). In your test(s), you can then mock the method(s) of that object in the following way:

makeMenusClient().getMenus.mockImplementation(() => [  { title: 'Brunch' },  { title: 'Dinner' }]);

Bear in mind that you need to import your module at the top of your test file so that you can invoke it and mock whichever method you’d like to mock.

This article and the GitHub Gist have been inspired by the following StackOverflow answer: https://stackoverflow.com/a/51534326/752391 thanks peoplenarthax.

--

--

Mattia Richetto

Engineering Leadership, Meditation, Running, and Yoga (in alphabetical order)