0

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?

Manpreet
  • 91
  • 1
  • 11

1 Answers1

1

Try this:

const mockStructuredClone = jest.fn();
global.structuredClone = () => mockStructuredClone();

it('should work', () => {
  mockStructuredClone.mockReturnValue({ test: 42 });

Marek Rozmus
  • 773
  • 7
  • 13