【问题标题】:Difficulty understanding mocked Jest functions难以理解模拟的 Jest 函数
【发布时间】:2021-01-17 13:43:26
【问题描述】:

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

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

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

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

一个组件代码示例是

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

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

const ageRange value = ageFunc(customerPropValues);

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

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

【问题讨论】:

    标签: reactjs unit-testing testing jestjs


    【解决方案1】:

    我不确定我是否完全理解它,但是如果您需要模拟它以使其始终有效,您应该模拟实现以使其始终返回相同的东西。你可以找到很多关于模拟自定义函数here

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

    有用的链接:link #1link #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'
        }));
    

    【讨论】:

    • // 导入前模拟 jest.mock('./mydir/helper/ageFunc') import ageFunc from './mydir/helper/ageFunc'; ageFunc.mockImplementation(() => '硬编码结果'));这不起作用,我正在使用打字稿,它抱怨'mockImplementation不是ageFunc的属性。
    • 这正是我正在寻找的东西。
    • @jobe 抱歉,我没有注意到它是一个命名导出。我更新了代码,使其适用于{ ageFunc }
    • 非常感谢您的工作!你能不能解释一下这里发生的步骤以及它是如何被嘲笑和使用的,我真的很想明白这一点。谢谢
    • 也许如果你找到了一个很好的文章或链接,因为我发现的那些很难理解而且有点深。
    猜你喜欢
    • 2014-05-16
    • 1970-01-01
    • 1970-01-01
    • 2016-01-05
    • 1970-01-01
    • 1970-01-01
    • 2018-09-14
    • 2022-06-29
    • 1970-01-01
    相关资源
    最近更新 更多