简体   繁体   English

如何使用Jest模拟非默认导入

[英]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. 我需要确保用正确的参数调用了externalFunction并对其进行了调用。

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. 解决方案:我需要将jest.mock调用带到任何测试或任何其他函数之外,因为jest需要提升它。 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: 最简单的方法之一是导入库并使用jest.spyOn监视该方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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