How do you spy on structuredClone() using Jest?

582 Views Asked by At

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

There are 1 best solutions below

0
On

Try this:

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

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