Reactjs 难以理解模拟的Jest函数

Reactjs 难以理解模拟的Jest函数,reactjs,unit-testing,testing,jestjs,Reactjs,Unit Testing,Testing,Jestjs,我有一个测试文件来测试React组件 React组件使用一些辅助函数来计算一些事情,例如,接收客户的出生日期,并根据他们的年龄是否在某个范围内返回一个数字 在测试文件中,我传递这些值,以便今天的测试通过,但我需要模拟它,以便始终通过 我知道我需要模拟正在组件中导入的helper函数,但我就是搞不清楚这一点 下面是一个组件代码示例 import { ageFunc } from './mydir/helper/ageFunc'; 然后它与传递到组件中的一些道具一起使用: const ageRan

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

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

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

我知道我需要模拟正在组件中导入的helper函数,但我就是搞不清楚这一点

下面是一个组件代码示例

import { ageFunc } from './mydir/helper/ageFunc';
然后它与传递到组件中的一些道具一起使用:

const ageRange value = ageFunc(customerPropValues);
然后,该AGrange值决定是否渲染某些内容


在测试文件中,我传递了有效的客户生日值,以触发我期望的呈现行为。我如何用mock设置它呢?

我不确定我是否完全理解它,但是如果需要对它进行模拟以使其始终工作,那么应该对实现进行模拟以使其始终返回相同的内容。您可以了解许多有关模拟自定义函数的信息

如果情况并非如此,您需要,但只想检查是否传递了正确的参数,或是否收到了正确的结果,则可以执行以下操作:

// 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();
有用链接:

它是如何工作的

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

从“/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'
    }));

//在导入jest.Mock('./mydir/helper/ageFunc')之前进行Mock。从'./mydir/helper/ageFunc'导入ageFunc;ageFunc.mockImplementation(()=>“硬代码结果”);这不起作用,我正在使用typescript,它抱怨“mockImplementation不是ageFunc的属性。但这正是我要找的东西。@jobe抱歉,我没有注意到它是命名导出。我更新了代码,这样它就可以为
{ageFunc}
工作了,非常感谢!请你解释一下这里发生的步骤,以及它是如何被嘲笑和使用的,我真的很想让我的头脑明白这一点。如果你找到一篇好文章或链接,谢谢你,因为我发现这些文章很难理解,而且有点深奥。
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'
    }));