如何使用Jest监视并模拟structuredClone()方法?
正确模拟structuredClone的Jest方案
你遇到的问题根源是Jest运行的Node环境默认没有structuredClone全局API,所以直接spyOn或者错误地用模块mock都会失败。以下是两种可行的解决方法:
方法一:直接在测试文件中挂载并模拟
先在全局对象上定义structuredClone,再赋予模拟实现:
const { cloneDeep } = require('lodash'); // 你可以替换为自己的深拷贝实现 // 挂载全局属性并设置mock global.structuredClone = jest.fn((value) => cloneDeep(value));
如果需要后续动态修改mock实现,也可以先挂载再用spyOn:
global.structuredClone = jest.fn(); jest.spyOn(global, 'structuredClone').mockImplementation((value) => cloneDeep(value));
方法二:全局前置配置(推荐)
在Jest的setupFilesAfterEnv配置文件(比如src/setupTests.js)中添加全局模拟,所有测试文件都会自动生效:
const { cloneDeep } = require('lodash'); global.structuredClone = jest.fn((value) => cloneDeep(value));
错误原因说明
- 第一种尝试失败:
global上原本不存在structuredClone属性,jest.spyOn只能监视已存在的函数属性,所以会提示属性未定义。 - 第二种尝试失败:
jest.mock是用来模拟npm模块的,而structuredClone是浏览器/现代Node的全局API,不是模块,因此会提示找不到模块。
验证模拟生效
测试用例中可以验证mock是否被正确调用:
test('目标函数调用了structuredClone', () => { const testData = { foo: 'bar', nested: { key: 'value' } }; // 调用你自己的、使用了structuredClone的业务函数 yourBusinessFunction(testData); // 断言mock被正确触发 expect(global.structuredClone).toHaveBeenCalledWith(testData); });
内容的提问来源于stack exchange,提问作者Avtar
相关产品推荐
相关产品推荐

