11

When I run jest tests locally with yarn test:unit:watch, I am getting this error from the jest library:

Test suite failed to run

TypeError: Cannot redefine property: window

at Object.<anonymous> (node_modules/jest-canvas-mock/lib/index.js:11:17)

Any suggestion what's wrong? I tried to delete node_modules and reinstall and also to clone the repo again but it's repeating. Others are not facing this problem.

Petr
  • 1,853
  • 2
  • 25
  • 49
  • I got such an error in our own testing codebase, and was able to fix it by creating a mock implementation following this answer: https://stackoverflow.com/a/56999581 – marcw Apr 21 '23 at 07:03

3 Answers3

12

In addition to mockImplementation approach mentioned by @marcw (link) and since I used Object.create approach from the same thread (link), I was able to solve the issue by changing

global.window = Object.create(window);

to

global.window ??= Object.create(window);
dhilt
  • 18,707
  • 8
  • 70
  • 85
6

This was an issue in jest-canvas-mock that was fixed in 2.4.0.

Upgrading to 2.4.0 or later should resolve the issue, and allow use of node 18 or better.

sklnd
  • 4,471
  • 3
  • 21
  • 8
-4

I changed my node version from 18 to 16.10 and it fixed the problem.

Petr
  • 1,853
  • 2
  • 25
  • 49