如何使用Jest监视structuredClone()?

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

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.

  1. .spyOn(global, 'structuredClone')
  2. .mockImplementation((value) => cloneDeep(value));

Cannot spy the structuredClone property because it is not a function; undefined given instead

  1. jest.mock('global.structuredClone', () =>
  2. jest.fn().mockImplementation((value) => cloneDeep(value))
  3. );

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.

  1. jest
  2. .spyOn(global, 'structuredClone')
  3. .mockImplementation((value) => cloneDeep(value));

> Cannot spy the structuredClone property because it is not a function; undefined given instead

  1. jest.mock('global.structuredClone', () =>
  2. jest.fn().mockImplementation((value) => cloneDeep(value))
  3. );

> Cannot find module 'structuredClone' from ...

How can I mock the implementation using Jest?

答案1

得分: 1

以下是您要翻译的内容:

尝试这个:

  1. const mockStructuredClone = jest.fn();
  2. global.structuredClone = () => mockStructuredClone();
  3. it('应该工作', () => {
  4. mockStructuredClone.mockReturnValue({ test: 42 });
英文:

Try this:

  1. const mockStructuredClone = jest.fn();
  2. global.structuredClone = () => mockStructuredClone();
  3. it('should work', () => {
  4. 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:

确定