【问题标题】:jest.fn() v/s jest.mock()?jest.fn() 与 jest.mock()?
【发布时间】:2021-01-25 07:31:45
【问题描述】:

为了模拟 uuidv4,我正在使用这个:

import { v4 as uuidv4 } from "uuid";
jest.mock("uuid");
uuidv4.mockReturnValue("uuid123");

对于模拟 window.confirm,我使用的是这个:

window.confirm = jest.fn().mockImplementation(() => true);

这两者都工作得很好。 但是当我尝试这样做时,即

const uuidv4 = jest.fn.mockImplementation(() => "uuid123");

我收到此错误

TypeError: jest.fn.mockImplementation is not a function

我对 jest.fn() 和 jest.mock() 感到困惑。

有人可以详细说明使用哪个以及何时使用,并提供合适的示例吗?

【问题讨论】:

  • 在您的第二个 jest.fn 中,您并没有调用它。一个你成功的问题是你的模拟函数是如何被你正在测试的代码使用的。这就是 jest.mock 的帮助。
  • 我在测试中调用它, const id = uuidv4();那是我收到此错误的时候。
  • @kob003 jest.fn.mockImplementation() 和 jest.fn().mockImplementation() 不是一回事。前者是错误的,后者是。 .无论您在哪里调用 uuidv4() 都是另一回事,因为如果您不正确使用 API,您将无法达到这一点。检查文档,它包含执行此操作的必要示例。

标签: unit-testing jestjs mocking


【解决方案1】:

简单解释一下:

  • jest.mock 是模拟某个模块。一旦你写了jest.mock('uuid'),就意味着所有导出的东西都会变成jest.Mock类型,这就是为什么你可以模拟v4方法:v4.mockReturnValue('yourV4Id');
jest.mock('aModule');

import {aMember} from "aModule";

// is now a jest mock type <=> jest.fn()
aMember.mockReturnValue('a value');

  • jest.fn 是一个函数,它返回一个 jest.Mock 类型,它可以被认为是一个函数来创建你想要的任何东西:
const aMock = jest.fn().mockReturnValue(1) // <=> const aMock = () => 1;

// The difference is jest mock type can be used to assert then. Most of cases is to check
// whether it gets called or not

【讨论】:

    猜你喜欢
    • 2021-11-18
    • 2017-04-26
    • 2020-11-02
    • 1970-01-01
    • 2021-12-20
    • 2019-06-16
    • 2017-12-24
    • 2020-06-09
    • 1970-01-01
    相关资源
    最近更新 更多