CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-jest-canvas-mock

Mock canvas when run unit test cases with jest.

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

Jest Canvas Mock

Jest Canvas Mock is a comprehensive canvas mocking library designed specifically for Jest testing environments. It provides a complete mock implementation of the HTML5 Canvas API that enables developers to test canvas-dependent code without running in a browser. The library implements all standard canvas functions with proper parameter validation, error handling that matches browser behavior, and provides additional testing utilities for snapshot testing and test assertions.

Package Information

  • Package Name: jest-canvas-mock
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install --save-dev jest-canvas-mock

Core Imports

import 'jest-canvas-mock';

CommonJS:

require('jest-canvas-mock');

For manual setup:

import { setupJestCanvasMock } from 'jest-canvas-mock';

Basic Usage

Automatic Setup

Add to your package.json Jest configuration:

{
  "jest": {
    "setupFiles": ["jest-canvas-mock"]
  }
}

Manual Setup

import { setupJestCanvasMock } from 'jest-canvas-mock';

beforeEach(() => {
  jest.resetAllMocks();
  setupJestCanvasMock();
});

Testing Canvas Operations

// Create canvas element
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');

// Perform canvas operations
ctx.fillStyle = '#ff0000';
ctx.fillRect(10, 10, 100, 100);
ctx.strokeStyle = '#00ff00';
ctx.strokeRect(20, 20, 80, 80);

// Test with snapshots
expect(ctx.__getEvents()).toMatchSnapshot();
expect(ctx.__getDrawCalls()).toMatchSnapshot();

Architecture

Jest Canvas Mock is built around several key components:

  • Canvas API Mock: Complete implementation of CanvasRenderingContext2D with all standard methods and properties
  • Error Simulation: Matches browser error behavior for invalid inputs (TypeError, DOMException, RangeError)
  • Event Tracking: Records all canvas operations for testing and debugging
  • Draw Call Tracking: Separates actual drawing operations from state changes
  • Path Tracking: Monitors path construction and modification
  • Browser APIs: Mocks related browser APIs like Path2D, ImageData, createImageBitmap
  • Jest Integration: All methods are Jest mock functions with full spy capabilities

Capabilities

Setup and Configuration

Manual setup and configuration functions for controlling the mock behavior.

function setupJestCanvasMock(window?: Window): void;
const ver: string;

Setup and Configuration

Canvas Context Mock

Complete implementation of CanvasRenderingContext2D with all standard drawing methods, transformations, and properties. Includes comprehensive error handling that matches browser behavior.

interface CanvasRenderingContext2D {
  // Drawing methods
  fillRect(x: number, y: number, width: number, height: number): void;
  strokeRect(x: number, y: number, width: number, height: number): void;
  clearRect(x: number, y: number, width: number, height: number): void;
  
  // Path methods  
  beginPath(): void;
  closePath(): void;
  moveTo(x: number, y: number): void;
  lineTo(x: number, y: number): void;
  arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, anticlockwise?: boolean): void;
  
  // Fill and stroke
  fill(fillRule?: CanvasFillRule): void;
  fill(path: Path2D, fillRule?: CanvasFillRule): void;
  stroke(): void;
  stroke(path: Path2D): void;
  
  // Text
  fillText(text: string, x: number, y: number, maxWidth?: number): void;
  strokeText(text: string, x: number, y: number, maxWidth?: number): void;
  measureText(text: string): TextMetrics;
  
  // Images
  drawImage(image: CanvasImageSource, dx: number, dy: number): void;
  drawImage(image: CanvasImageSource, dx: number, dy: number, dw: number, dh: number): void;
  drawImage(image: CanvasImageSource, sx: number, sy: number, sw: number, sh: number, dx: number, dy: number, dw: number, dh: number): void;
  
  // Transformations
  scale(x: number, y: number): void;
  rotate(angle: number): void;
  translate(x: number, y: number): void;
  transform(a: number, b: number, c: number, d: number, e: number, f: number): void;
  setTransform(a: number, b: number, c: number, d: number, e: number, f: number): void;
  setTransform(transform?: DOMMatrix2DInit): void;
  resetTransform(): void;
  
  // State
  save(): void;
  restore(): void;
  
  // Properties (getters/setters)
  fillStyle: string | CanvasGradient | CanvasPattern;
  strokeStyle: string | CanvasGradient | CanvasPattern;
  lineWidth: number;
  font: string;
  textAlign: CanvasTextAlign;
  textBaseline: CanvasTextBaseline;
  // ... many more properties
}

Canvas Context Mock

Test Utilities

Special testing methods added to CanvasRenderingContext2D for Jest testing. These methods track canvas operations and provide utilities for snapshot testing and assertions.

interface CanvasRenderingContext2D {
  __getEvents(): CanvasRenderingContext2DEvent[];
  __clearEvents(): void;
  __getDrawCalls(): CanvasRenderingContext2DEvent[];
  __clearDrawCalls(): void;
  __getPath(): CanvasRenderingContext2DEvent[];
  __clearPath(): void;
  __getClippingRegion(): CanvasRenderingContext2DEvent[];
}

interface CanvasRenderingContext2DEvent {
  type: string;
  transform: [number, number, number, number, number, number];
  props: { [key: string]: any };
}

Test Utilities

Browser API Mocks

Mock implementations of browser APIs related to canvas functionality including Path2D, ImageData, TextMetrics, and other canvas-related classes.

class Path2D {
  constructor(path?: Path2D | string);
  addPath(path: Path2D, transform?: DOMMatrix2DInit): void;
  closePath(): void;
  moveTo(x: number, y: number): void;
  lineTo(x: number, y: number): void;
  arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, anticlockwise?: boolean): void;
  // ... more path methods
}

class ImageData {
  constructor(width: number, height: number);
  constructor(data: Uint8ClampedArray, width: number, height?: number);
  readonly width: number;
  readonly height: number;
  readonly data: Uint8ClampedArray;
}

function createImageBitmap(
  image: ImageBitmapSource,
  options?: ImageBitmapOptions
): Promise<ImageBitmap>;

function createImageBitmap(
  image: ImageBitmapSource,
  sx: number, sy: number, sw: number, sh: number,
  options?: ImageBitmapOptions
): Promise<ImageBitmap>;

Browser API Mocks

Types

type CanvasImageSource = HTMLImageElement | SVGImageElement | HTMLVideoElement | HTMLCanvasElement | ImageBitmap | OffscreenCanvas;

type CanvasFillRule = "nonzero" | "evenodd";

type CanvasTextAlign = "start" | "end" | "left" | "right" | "center";

type CanvasTextBaseline = "top" | "hanging" | "middle" | "alphabetic" | "ideographic" | "bottom";

interface ImageBitmapOptions {
  imageOrientation?: "none" | "flipY";
  premultiplyAlpha?: "none" | "premultiply" | "default";
  colorSpaceConversion?: "none" | "default";
  resizeWidth?: number;
  resizeHeight?: number;
  resizeQuality?: "pixelated" | "low" | "medium" | "high";
}

interface DOMMatrix2DInit {
  a?: number;
  b?: number;
  c?: number;
  d?: number;
  e?: number;
  f?: number;
  m11?: number;
  m12?: number;
  m21?: number;
  m22?: number;
  m41?: number;
  m42?: number;
}
Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/jest-canvas-mock@2.5.x
Publish Source
CLI
Badge
tessl/npm-jest-canvas-mock badge