wobsoriano / vitest-canvas-mock

🌗 A module used to mock canvas in Vitest.
MIT License
54 stars 9 forks source link

fix: guard against window being absent in global #11

Open gthb opened 8 months ago

gthb commented 8 months ago

A vitest test configured to run in a non-browser environment, e.g. with a comment like this at the top:

/*
* @vitest-environment node
*/

... fails when vitest-canvas-mock is installed and enabled, because window does not exist in the global object:

ReferenceError: window is not defined
 ❯ importMockWindow node_modules/vitest-canvas-mock/dist/index.js:17:52

So guard against this case by acting only when window is present in global.

Tested this change in my project using patch-package with this patch:

diff --git a/node_modules/vitest-canvas-mock/dist/index.js b/node_modules/vitest-canvas-mock/dist/index.js
index f03ec66..3cbc2fa 100644
--- a/node_modules/vitest-canvas-mock/dist/index.js
+++ b/node_modules/vitest-canvas-mock/dist/index.js
@@ -20,8 +20,12 @@ async function importMockWindow() {
     global.window[api] = canvasWindow[api];
   });
 }
-importMockWindow();
+if ('window' in global) {
+  importMockWindow();
+}
 afterAll(() => {
   delete global.jest;
-  delete global.window.jest;
+  if ('window' in global) {
+    delete global.window.jest;
+  }
 });
JCMais commented 2 months ago

I had to apply the same patch.