Skip to content
Latchkey

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)".

Vitest
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

  1. Add the canvas npm package so jsdom has a real 2D backend.
  2. Note it needs system build dependencies on some runners.
  3. Re-run so getContext returns a context.
Terminal
npm install -D canvas

Mock getContext in setup

If you do not assert on drawing, stub getContext in a setup file so tests do not need a real backend.

src/test/setup.ts
HTMLCanvasElement.prototype.getContext = () => ({})

How to prevent it

  • Install canvas when tests actually render to a canvas.
  • Mock getContext when drawing output is not under test.
  • Keep graphics-heavy tests isolated so their deps are explicit.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →