如何使用Jest监视structuredClone()?

huangapple go评论86阅读模式
英文:

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 });

huangapple
  • 本文由 发表于 2023年3月4日 00:51:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/75629816.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定