在 Jest 中模拟导入函数

und*_*ood 15 javascript unit-testing reactjs jestjs

我有一个案例:

test.js

import { today } from "utils/date";
import myFunction from "helpers/myFunction";

it('should work properly', () => {
   jest.mock('utils/date', () => ({
      ...(jest.requireActual('utils/date')),
      today: jest.fn(() => '01-01-2020'),
   }));

   console.log(today()); // still logs current date 14-10-2021, not the mocked date       

   expect(myFunction()).toEqual(today());
});
Run Code Online (Sandbox Code Playgroud)

myFunction.js

import { today } from "utils/date";

export const myFunction = () => today();
Run Code Online (Sandbox Code Playgroud)

today是一个返回今天日期的函数。但出于测试目的,我需要该函数始终返回相同的日期,例如"01-01-2020"

注意:正如您所看到的,“today”函数在测试中以及被测试的 (myFunction) 函数中使用,因此它必须返回与应用程序中的所有位置相同的模拟值。

谢谢

sli*_*wp2 30

jest.mock()在测试用例功能范围内调用。模块导入被提升(内部移动到当前作用域的开头)。在模拟模块today之前导入原始函数。jest.mock()utils/date

您可以将jest.mock()测试用例功能范围移动到模块范围。Jest 会自动将调用jest.mock提升到模块的顶部(在任何导入之前)。这样当您导入该today函数时,它就已经被模拟了。

请参阅与 ES 模块导入一起使用

如果您使用 ES 模块导入,那么您通常会倾向于将import语句放在测试文件的顶部。但通常您需要在模块使用模拟之前指示 Jest 使用模拟。因此,Jest 会自动将调用jest.mock提升到模块的顶部(在任何导入之前)。

import { today } from 'utils/date';

jest.mock('utils/date', () => ({
  today: jest.fn(() => '01-01-2020'),
}));

it('should work properly', () => {
  expect(jest.isMockFunction(today)).toBeTruthy();
  expect(today()).toBe('01-01-2020');
});
Run Code Online (Sandbox Code Playgroud)