Vitest "Not implemented: HTMLCanvasElement.getContext" in CI
The jsdom and happy-dom environments provide a DOM but not a real canvas implementation. Code calling canvas.getContext('2d') hits a "Not implemented" error. Install the canvas package for a real backend, or mock getContext in setup.
What this error means
A DOM test fails with "Error: Not implemented: HTMLCanvasElement.prototype.getContext (without installing the canvas npm package)".
Error: Not implemented: HTMLCanvasElement.prototype.getContext (without installing
the canvas npm package)
at module.exports (/app/node_modules/jsdom/lib/jsdom/browser/not-implemented.js)Common causes
The DOM environment has no canvas backend
jsdom/happy-dom stub the canvas element but not its 2D/WebGL context, so getContext throws unless a backend is installed.
Charting/graphics code runs in tests
A component that draws to canvas (charts, image processing) exercises getContext during the test.
How to fix it
Install the canvas package
- Add the
canvasnpm package so jsdom has a real 2D backend. - Note it needs system build dependencies on some runners.
- Re-run so
getContextreturns a context.
npm install -D canvasMock getContext in setup
If you do not assert on drawing, stub getContext in a setup file so tests do not need a real backend.
HTMLCanvasElement.prototype.getContext = () => ({})How to prevent it
- Install
canvaswhen tests actually render to a canvas. - Mock
getContextwhen drawing output is not under test. - Keep graphics-heavy tests isolated so their deps are explicit.