简体   繁体   中英

How to Mock non-default import using Jest

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.

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
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM