diff --git a/.gitignore b/.gitignore index bc7a6d1..cbb0c3b 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,6 @@ coverage package-lock.json yarn.lock lib +.yarn +.pnp.cjs +.pnp.loader.mjs diff --git a/README.md b/README.md index 0aaf571..1f935c5 100644 --- a/README.md +++ b/README.md @@ -63,6 +63,20 @@ Add that file to your `setupFiles` array: } ``` +## Reset + +If you reset the jest mocks (for example, with `jest.resetAllMocks()`), you can +call `setupJestCanvasMock()` to re-create it. + +``` +import { setupJestCanvasMock } from 'jest-canvas-mock'; + +beforeEach(() => { + jest.resetAllMocks(); + setupJestCanvasMock(); +}); +``` + ## Mock Strategy This mock strategy implements all the canvas functions and actually verifies the parameters. If a diff --git a/__tests__/index.js b/__tests__/index.js index dd9354f..300c85d 100644 --- a/__tests__/index.js +++ b/__tests__/index.js @@ -2,7 +2,7 @@ * test canvas */ -import { ver } from '../src'; +import { ver, setupJestCanvasMock } from '../src'; import pkg from '../package.json'; let canvas; @@ -16,3 +16,14 @@ describe('canvas', () => { expect(ver).toBe(pkg.version); }); }); + +describe('setupJestCanvasMock', () => { + it('should setup after resetAllMocks', () => { + jest.resetAllMocks(); + expect(document.createElement('canvas').getContext('2d')).toBe(undefined); + setupJestCanvasMock(); + expect(document.createElement('canvas').getContext('2d')).toHaveProperty( + 'createImageData' + ); + }); +}); diff --git a/src/index.js b/src/index.js index f6e4994..aa1ec9a 100644 --- a/src/index.js +++ b/src/index.js @@ -12,3 +12,7 @@ if (typeof window !== 'undefined') { } export const ver = '__VERSION__'; + +export function setupJestCanvasMock(window) { + mockWindow(window || global.window); +} diff --git a/types/index.d.ts b/types/index.d.ts index 9882705..39a3edc 100644 --- a/types/index.d.ts +++ b/types/index.d.ts @@ -1,3 +1,5 @@ +export function setupJestCanvasMock(window?: Window) {} + export interface CanvasRenderingContext2DEvent { /** * This is the type of canvas event that occured.