首页 > 解决方案 > 难以理解模拟的 Jest 函数

问题描述

我有一个测试文件来测试一个 React 组件。

React 组件使用一些辅助函数来计算一些事情,例如获取客户的出生日期并根据他们的年龄是否在一定范围内返回一个数字。

在测试文件中,我传递了这些值,因此今天的测试将通过,但我需要模拟它以便始终通过。

我知道我需要模拟在组件中导入的辅助函数,但我就是想不通。

组件代码示例是

import { ageFunc } from './mydir/helper/ageFunc';

然后它与传递给组件的一些道具一起使用:

const ageRange value = ageFunc(customerPropValues);

然后这个 ageRange 值决定是否渲染某些东西。

在测试文件中,我传递了有效的客户生日值,以触发我期望的渲染行为。如何使用模拟进行设置?

标签: reactjsunit-testingtestingjestjs

解决方案


我不确定我是否完全理解它,但如果你需要模拟它以便它始终工作,你应该模拟实现,以便它总是返回相同的东西。你可以在这里找到很多关于模拟自定义函数的信息。

// Mock before importing
jest.mock('./mydir/helper/ageFunc', () => ({
  __esModule: true,
  default: () => 'Default',
  ageFunc : () => 'hardcoded result',
}));
import { ageFunc } from './mydir/helper/ageFunc';

const ageRange = ageFunc(customerPropValues); // ageRange returns 'Hardcode result'

如果不是这种情况,您想要,但只是想检查是否传递了正确的参数,或者收到了正确的结果,您可以执行以下一些操作:

// The mock function was called at least once
expect(ageFunc).toHaveBeenCalled();

// The mock function was called at least once with the specified arguments
expect(ageFunc).toHaveBeenCalledWith(arg1, arg2);

// The last call to the mock function was called with the specified arguments
expect(ageFunc).toHaveBeenLastCalledWith(arg1, arg2);

// All calls and the name of the mock is written as a snapshot
expect(ageFunc).toMatchSnapshot();

有用的链接:链接#1 链接#2

它是如何工作的?

让我们从一个默认模块的简单示例开始:

import a from './path'

我们模拟这个的方式是:

jest.mock('./path')
import a from './path'

这个测试文件会将模拟函数读入a变量。

现在对于您的案例,您有一个命名导出,因此案例有点复杂。

import { a } from './path'

为了模拟这一点,我们必须扩展jest.mock一点。

jest.mock('./path', () => ({
      __esModule: true, // Settings to make it behave as an ECMAScript module
      default: () => 'Default', // Mock the default export (import a from './dir')
      a: () => 'hardcoded result', // Mock the named export (import { a } from './dir'
    }));

推荐阅读