How to Mock non-default import using Jest

Viewed 2635

How can I mock a function that is being imported inside the file that contains the function I am testing?

without putting it in the mocks folder.

// FileIWantToTest.js
import { externalFunction } from '../../differentFolder';

export const methodIwantToTest = (x) => { externalFunction(x + 1) }

I need to make sure that externalFunction is called and its called with the correct arguments.

Seems super simple but the documentation doesn't cover how to do this without mocking the module for all the files in the test by putting the mocks in the mocks folder.

2 Answers

The solution: I need to take my jest.mock call outside of any test or any other function because jest needs to hoist it. Also for named exports like in my case I also have to use the following syntax:

jest.mock('../../differentFolder', () => ({
  __esModule: true,
  externalFunction: jest.fn(),
 }));

One of the easiest approaches is to import the library and use jest.spyOn to spy on the method:

import { methodIwantToTest } from './FileIWantToTest';
import * as lib from '../../differentFolder';  // import the library containing externalFunction

test('methodIwantToTest', () => {
  const spy = jest.spyOn(lib, 'externalFunction');  // spy on externalFunction
  methodIwantToTest(1);
  expect(spy).toHaveBeenCalledWith(2);  // SUCCESS
});
Related