wobsoriano / vitest-canvas-mock

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

ReferenceError: jest is not defined #4

Closed wojtekmaj closed 1 year ago

wojtekmaj commented 1 year ago

This is the error I faced when testing react-pdf:

ReferenceError: jest is not defined
 ❯ node_modules/jest-canvas-mock/lib/classes/CanvasRenderingContext2D.js:161:19
 ❯ new CanvasRenderingContext2D node_modules/jest-canvas-mock/lib/classes/CanvasRenderingContext2D.js:160:15
 ❯ HTMLCanvasElement.getContext2d node_modules/jest-canvas-mock/lib/mock/prototype.js:28:19
 ❯ HTMLCanvasElement.<anonymous> ../../Open%20source%20projects/react-pdf/node_modules/@vitest/spy/dist/index.js:112:17
 ❯ HTMLCanvasElement.getContext2d [as getContext] ../../Open%20source%20projects/react-pdf/node_modules/tinyspy/dist/index.js:30:20
 ❯ Object.canvasContext src/Page/PageCanvas.jsx:91:23
alcasas commented 1 year ago

@wojtekmaj I'm having same issue, do you know how to solve it ?

treardon17 commented 1 year ago

I'm also having this issue

alcasas commented 1 year ago

I'm also having this issue

@treardon17

I ended up forking jest-canvas-mock in a my github and doing the following:

this is the content of vitest-canvas-mock.ts:

import { afterAll, vi } from 'vitest';
// @ts-expect-error: Global type missing
global.jest = vi;
// eslint-disable-next-line import/first
import getCanvasWindow from 'jest-canvas-mock/src/window'; // here is my fork with changes in the code

const apis = [
  'Path2D',
  'CanvasGradient',
  'CanvasPattern',
  'CanvasRenderingContext2D',
  'DOMMatrix',
  'ImageData',
  'TextMetrics',
  'ImageBitmap',
  'createImageBitmap',
] as const;

const canvasWindow = getCanvasWindow({ document: window.document });

apis.forEach((api) => {
  global[api] = canvasWindow[api];
  global.window[api] = canvasWindow[api];
});

afterAll(() => {
  delete global.jest;
  delete global.window.jest;
});
treardon17 commented 1 year ago

@alcasas thanks for the tip!

nickyvanurk commented 1 year ago

I'm having this problem as well. The fix by @alcasas didn't work.

wobsoriano commented 1 year ago

@nickyvanurk you can probs do this for now

import { afterAll, vi } from 'vitest';
global.jest = vi;

declare global {
  var jest: typeof vi | undefined
}

Add that in a setup file.

wobsoriano commented 1 year ago

Please reopen if the issue continues to exist.

alcasas commented 10 months ago

@nickyvanurk you need to look into the error, then see where is failing, for sure is a method referenced to jest that doesn't exists, so you need to change it in your forked repository to not use that specific reference