npm uuid]版本更新后Mocking不起作用

问题描述 投票:0回答:1

更新到9.0.1版本后,我无法在Jest中模拟'v4'的返回值。 jest.mock('uuid')、jest.spyOn(uuid, 'v4') 和 jest.replaceProperty(uuid, 'v4') 都不起作用。我的 Jest 版本是 29.3.1。有解决办法吗?

jest.mock('uuid') 参考错误:未定义要求

jest.spyOn(uuid, 'v4') 无法监视 v4 属性,因为它不是函数;改为未定义。如果您尝试模拟属性,请使用

jest.replaceProperty(object, 'v4', value)
代替。

jest.replaceProperty(uuid, 'v4') v4 属性不存在

import { uuid }  from 'uuid' // version 9.0.1

...
jest.spyOn(uuid, 'uuid').toImplementationOnce(2); <- occur error (Cannot Spy on the v4 property because it is not a function; undefined given instead)
...
node.js jestjs uuid
1个回答
0
投票

我在这个包的命名导出中没有看到

uuid
https://www.npmjs.com/package/uuid

当您将所有命名导入作为默认导入导入时,这个技巧可能有效也可能无效,具体取决于包的构建方式。

通过正确寻址命名导出,可以毫无问题地模拟它:

import { v4 as uuid } from "uuid";

jest.mock("uuid");

it("uuid V4 can be mocked", () => {
  uuid.mockReturnValueOnce("2");
  expect(uuid()).toBe("2");
});
© www.soinside.com 2019 - 2024. All rights reserved.