jest-canvas-mock
jest-canvas-mock copied to clipboard
Can't use jest-canvas-mock without jest
Example setup needed to bootstrap jest manually that can be a pain point:
const jest = {
fn: (arg) => arg,
};
global.jest = jest;
const CanvasRenderingContext2D = require("jest-canvas-mock/lib/classes/CanvasRenderingContext2D").default;
const Path2D = require("jest-canvas-mock/lib/classes/Path2D").default;
global.Path2D = Path2D;
@hustcc is this something worth supporting?
I can not catch your problem, can give me a test case?
https://github.com/hustcc/jest-canvas-mock/blob/d89582496b40a66e490c6f37d4faec6ffce6bd85/src/window.js#L47
Is it because Path2D exists in jsdom? so mock failed?
Yeah. I recently had to bootstrap this library without using jest so I could test a few wasm simd functions in my canvas library. I want to think on this before I make any suggestions.
I believe this can be fixed by checking to see if jest
exists in the global scope. If it doesn't we can just polyfill jest.fn
to be an identity function.
Another really easy fix might also be to just import the Path2D
class directly instead of using the global version.
I find that using new CanvasRenderingContext2D(width, height)
is clunky for testing, but is very useful. Please see https://github.com/as2d/as2d as an example (which also uses jest, but manually bootstraps the canvas in the case of SIMD testing.)
I will likely start to tackle this soon. I feel like people should be able to import this module without having to do any setup.
This means testing the module without jest
in testing, and will require another test step.
I believe this is still worth using. Perhaps the core functionality of emulating the CanvasRenderingContext2D
class can be in it's own package?
I believe this is still worth using. Perhaps the core functionality of emulating the
CanvasRenderingContext2D
class can be in it's own package?
Change this repo to mono repo?
I don't entirely know the right answer. It would be nice for someone else to pick up the responsibility, because I'm only good at the canvas part. :)
You can get around this by importing the script inside of a setup module.
// jest.config.js
module.exports = {
setupFilesAfterEnv: ["./jest.setup.js"],
// other jest config
}
// jest.setup.js
require("jest-canvas-mock")
\\ jest setup stuff
Essentially the setup file works like a before block, so it's already in a jest context.
This should remove the jest global error.
I'm having similar issues but for a totally separate reason. I like to use jest with the injectGlobals
config variable set, so anything from jest has to be explicitly imported (rather than letting jest pollute the global namespace). However, I cannot do that with jest-canvas-mock because it assumes the jest global will be available everywhere. In my case, explicitly importing jest where it's used would solve the issue and make it compatible with injectGlobals
.