Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

index: export a function to re-initialize mocks #98

Merged
merged 5 commits into from
Nov 28, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,6 @@ coverage
package-lock.json
yarn.lock
lib
.yarn
.pnp.cjs
.pnp.loader.mjs
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
13 changes: 12 additions & 1 deletion __tests__/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
* test canvas
*/

import { ver } from '../src';
import { ver, setupJestCanvasMock } from '../src';
import pkg from '../package.json';

let canvas;
Expand All @@ -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'
);
});
});
4 changes: 4 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,7 @@ if (typeof window !== 'undefined') {
}

export const ver = '__VERSION__';

export function setupJestCanvasMock(window) {
mockWindow(window || global.window);
}
2 changes: 2 additions & 0 deletions types/index.d.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
export function setupJestCanvasMock(window?: Window) {}

export interface CanvasRenderingContext2DEvent {
/**
* This is the type of canvas event that occured.
Expand Down