【问题标题】:Mock imported function in Jest在 Jest 中模拟导入函数
【发布时间】:2021-10-14 15:36:47
【问题描述】:

我有一个案例:

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

myFunction.js

import { today } from "utils/date";

export const myFunction = () => today();

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

注意:正如您所见,“today”函数用于测试以及被测试的 (myFunction) 函数内部,因此它必须像应用程序中的任何地方一样返回相同的模拟值。

谢谢

【问题讨论】:

    标签: javascript reactjs unit-testing jestjs


    【解决方案1】:

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

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

    Using with ES module imports:

    如果您使用 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');
    });
    

    【讨论】:

      猜你喜欢
      • 2018-06-30
      • 2017-02-06
      • 1970-01-01
      • 1970-01-01
      • 2020-02-26
      • 2020-08-04
      • 2019-09-19
      • 1970-01-01
      • 2019-02-25
      相关资源
      最近更新 更多