英文:
How do you spy on structuredClone() using Jest?
问题
I want to spy on the structuredClone method and mock its implementation because when running Jest tests, I get this error:
ReferenceError: structuredClone is not defined
I've tried both spying and mocking as below, but I got errors with both.
.spyOn(global, 'structuredClone')
.mockImplementation((value) => cloneDeep(value));
Cannot spy the structuredClone property because it is not a function; undefined given instead
jest.mock('global.structuredClone', () =>
jest.fn().mockImplementation((value) => cloneDeep(value))
);
Cannot find module 'structuredClone' from ...
How can I mock the implementation using Jest?
英文:
I want to spy on the structuredClone method and mock its implementation because when running Jest tests, I get this error:
> ReferenceError: structuredClone is not defined
I've tried both spying and mocking as below, but I got errors with both.
jest
.spyOn(global, 'structuredClone')
.mockImplementation((value) => cloneDeep(value));
> Cannot spy the structuredClone property because it is not a function; undefined given instead
jest.mock('global.structuredClone', () =>
jest.fn().mockImplementation((value) => cloneDeep(value))
);
> Cannot find module 'structuredClone' from ...
How can I mock the implementation using Jest?
答案1
得分: 1
以下是您要翻译的内容:
尝试这个:
const mockStructuredClone = jest.fn();
global.structuredClone = () => mockStructuredClone();
it('应该工作', () => {
mockStructuredClone.mockReturnValue({ test: 42 });
英文:
Try this:
const mockStructuredClone = jest.fn();
global.structuredClone = () => mockStructuredClone();
it('should work', () => {
mockStructuredClone.mockReturnValue({ test: 42 });
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论