Mock canvas when run unit test cases with jest.
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
Manual setup and configuration functions for controlling the jest-canvas-mock behavior. Use these functions when you need fine-grained control over mock initialization or when working with custom test setups.
Manually initializes or reinitializes the canvas mock on a specified window object. This is useful when you need to reset mocks during testing or when working with custom window objects.
/**
* Sets up canvas mocking on the specified window object or global.window
* @param window - Optional window object to mock, defaults to global.window
*/
function setupJestCanvasMock(window?: Window): void;Access to the package version string for debugging and compatibility checks.
/**
* Package version string - useful for debugging and compatibility checks
*/
const ver: string;Usage Examples:
import { setupJestCanvasMock, ver } from 'jest-canvas-mock';
// Check package version
console.log('jest-canvas-mock version:', ver);
// Conditional behavior based on version
if (ver === '2.5.2') {
// Version-specific setup
}
// Basic usage - uses global.window
setupJestCanvasMock();
// With custom window object
setupJestCanvasMock(customWindow);
// Common pattern - reset mocks before each test
beforeEach(() => {
jest.resetAllMocks();
setupJestCanvasMock();
});
// Setup after clearing Jest mocks
afterEach(() => {
jest.clearAllMocks();
setupJestCanvasMock();
});For most use cases, automatic setup via Jest configuration is recommended:
{
"jest": {
"setupFiles": ["jest-canvas-mock"]
}
}{
"jest": {
"setupFiles": [
"./__setups__/other.js",
"jest-canvas-mock"
]
}
}Create a setup file that imports jest-canvas-mock:
// __setups__/canvas.js
import 'jest-canvas-mock';
// or
require('jest-canvas-mock');Then reference it in package.json:
{
"jest": {
"setupFiles": ["./__setups__/canvas.js"]
}
}The setup function performs the following operations:
Global API Mocking: Adds mock implementations of canvas-related classes to the window object:
Path2DCanvasGradientCanvasPatternCanvasRenderingContext2DDOMMatrixImageDataTextMetricsImageBitmapcreateImageBitmapHTMLCanvasElement Extension: Overrides methods on HTMLCanvasElement.prototype:
getContext() - Returns mock 2D contexttoBlob() - Mock implementation with proper error handlingtoDataURL() - Returns mock data URLJest Integration: All mocked methods are Jest mock functions with full spy capabilities
The mock is designed to work in various Jest environments:
The setup process is robust and handles various edge cases: