• Stars
    star
    300
  • Rank 138,870 (Top 3 %)
  • Language
    JavaScript
  • Created almost 7 years ago
  • Updated 9 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

🌗 A module used to mock canvas in Jest.

jest-canvas-mock

Mock canvas when run unit test cases with jest. For more browser environment, you can use jest-electron for real browser runtime.

Build Status Coverage Status npm npm Mentioned in Awesome Jest

Install

This should only be installed as a development dependency (devDependencies) as it is only designed for testing.

npm i --save-dev jest-canvas-mock

Setup

In your package.json under the jest, create a setupFiles array and add jest-canvas-mock to the array.

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

If you already have a setupFiles attribute you can also append jest-canvas-mock to the array.

{
  "jest": {
    "setupFiles": ["./__setups__/other.js", "jest-canvas-mock"]
  }
}

More about in configuration section.

Setup file

Alternatively you can create a new setup file which then requires this module or add the require statement to an existing setup file.

__setups__/canvas.js

import 'jest-canvas-mock';
// or
require('jest-canvas-mock');

Add that file to your setupFiles array:

"jest": {
  "setupFiles": [
    "./__setups__/canvas.js"
  ]
}

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 known condition would cause the browser to throw a TypeError or a DOMException, it emulates the error. For instance, the CanvasRenderingContext2D#arc function will throw a TypeError if the radius is negative, or if it was not provided with enough parameters.

// arc throws a TypeError when the argument length is less than 5
expect(() => ctx.arc(1, 2, 3, 4)).toThrow(TypeError);

// when radius is negative, arc throws a dom exception when all parameters are finite
expect(() => ctx.arc(0, 0, -10, 0, Math.PI * 2)).toThrow(DOMException);

The function will do Number type coercion and verify the inputs exactly like the browser does. So this is valid input.

expect(() => ctx.arc('10', '10', '20', '0', '6.14')).not.toThrow();

Another part of the strategy is to validate input types. When using the CanvasRenderingContext2D#fill function, if you pass it an invalid fillRule it will throw a TypeError just like the browser does.

expect(() => ctx.fill('invalid!')).toThrow(TypeError);
expect(() => ctx.fill(new Path2D(), 'invalid!')).toThrow(TypeError);

We try to follow the ECMAScript specification as closely as possible.

Snapshots

There are multiple ways to validate canvas state using snapshots. There are currently three methods attached to the CanvasRenderingContext2D class. The first way to use this feature is by using the __getEvents method.

/**
 * In order to see which functions and properties were used for the test, you can use `__getEvents`
 * to gather this information.
 */
const events = ctx.__getEvents();

expect(events).toMatchSnapshot(); // jest will assert the events match the snapshot

The second way is to inspect the current path associated with the context.

ctx.beginPath();
ctx.arc(1, 2, 3, 4, 5);
ctx.moveTo(6, 7);
ctx.rect(6, 7, 8, 9);
ctx.closePath();

/**
 * Any method that modifies the current path (and subpath) will be pushed to an event array. When
 * using the `__getPath` method, that array will sliced and usable for snapshots.
 */
const path = ctx.__getPath();
expect(path).toMatchSnapshot();

The third way is to inspect all of the successful draw calls submitted to the context.

ctx.drawImage(img, 0, 0);

/**
 * Every drawImage, fill, stroke, fillText, or strokeText function call will be logged in an event
 * array. This method will return those events here for inspection.
 */
const calls = ctx.__getDrawCalls();
expect(calls).toMatchSnapshot();

In some cases it may be useful to clear the events or draw calls that have already been logged.

// Clear events
ctx.__clearEvents();

// Clear draw calls
ctx.__clearDrawCalls();

Finally, it's possible to inspect the clipping region calls by using the __getClippingRegion function.

const clippingRegion = ctx.__getClippingRegion();
expect(clippingRegion).toMatchSnapshot();

The clipping region cannot be cleared because it's based on the stack values and when the .clip() function is called.

Override default mock return value

You can override the default mock return value in your test to suit your need. For example, to override return value of toDataURL:

canvas.toDataURL.mockReturnValueOnce(
  'data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='
);

Contributors

License

MIT@hustcc.

More Repositories

1

JS-Sorting-Algorithm

一本关于排序算法的 GitBook 在线书籍 《十大经典排序算法》,多语言实现。
Java
5,126
star
2

timeago.js

🕗 ⌛ timeago.js is a tiny(2.0 kb) library used to format date with `*** time ago` statement.
TypeScript
5,033
star
3

echarts-for-react

⛳️ Apache ECharts components for React wrapper. 一个简单的 Apache echarts 的 React 封装。
TypeScript
4,485
star
4

canvas-nest.js

♋ Interactive Particle / Nest System With JavaScript and Canvas, no jQuery.
JavaScript
4,278
star
5

PyG2Plot

🎨 Python3 binding for `@AntV/G2Plot` Plotting Library .
Python
1,012
star
6

PTHospital.chrome

⚠️ 🏥 Chrome浏览器插件——打开莆田系医院网站,发出警告提醒、显示医院信息。
JavaScript
573
star
7

onfire.js

🔫 onfire.js is a nano version (~500b) for event-emitter.
TypeScript
498
star
8

timeago-react

🕗 Simple and efficient react component to format date with `*** time ago` statement. eg: '3 hours ago'.
TypeScript
421
star
9

xmorse

🌞 ~1.5Kb morse code library for all. 一个支持 Unicode 中文摩斯密码编码的 Javascript 库。
TypeScript
312
star
10

gantt-for-react

🌿 Frappe Gantt components for React wrapper. 一个简单的甘特图 React 组件封装。
JavaScript
291
star
11

react-adsense

📽️ a simple React-component for Google AdSense / Baidu advertisement.
JavaScript
263
star
12

jest-date-mock

🌗 Mock `Date` when run unit test cases with jest. Make tests of Date easier.
JavaScript
259
star
13

timeago

⌛ Simple library used to format datetime with `*** time ago` statement. eg: "3 hours ago".
Python
223
star
14

ribbon.js

🎀 Only 1kb javascript gist to generate a ribbon in your website with HTML5 canvas.
JavaScript
219
star
15

webhookit

:octocat: Simple git webhook cli tool for automation tasks, bind git webhook to action.
Python
192
star
16

alimask

😷 alimask 是一个使用 canvas 生成类似阿里巴巴内部网站水印图片的 JavaScript 库。
JavaScript
176
star
17

size-sensor

🌿 1Kb DOM element size sensor which will callback when size changed.
JavaScript
165
star
18

placeholder.js

⚡ < 1Kb library to generate image placeholders on client side
PHP
161
star
19

jest-electron

❯ ⚛️The easiest way to run and debug test cases in electron with jest.
TypeScript
144
star
20

chrome-qrcode

⚡ A Chrome plugin to Genrate QRCode of URL / Text, or Decode the QRcode in website. 一个Chrome浏览器插件,用于生成当前URL或者选中内容的二维码,同时可以用于解析网页上的二维码内容。
JavaScript
133
star
21

iReact

🎁 iReact: Fantastic React Components and Libraries! Makes it easy for you to pick one that’ll work for you.
JavaScript
82
star
22

mac.py

⚡A python lib to search Manufacturer of physical network card by mac address. 一个通过物理地址查询网卡所属厂商的Python库。
Python
68
star
23

pixi-action

🏇 pixi-action is a plugin for Pixi.js to create actions and animations easily, inspired by Cocos2d-x.
HTML
65
star
24

word-table

◼️ a simple javascript (browserjs / nodejs) library for drawing tables in the terminal / console, unicode supported.
JavaScript
60
star
25

wrapcache

⚡ A python Function / Method OUTPUT cache system base on function Decorators.
Python
58
star
26

simple-shields

🔰 a simple Shields Badge service with PHP & SVG, Simple, Fast, Stable and Easy Deploy.
HTML
50
star
27

GitHub-Helper.Chrome

:octocat: A Chrome plugin for GitHub Helper. Get a better idea about GitHub.
CSS
40
star
28

GitHub-Repo-Widget.js

:octocat: A good looking github repository widget to add to your website. Not depends on jQuery or Other.
JavaScript
39
star
29

aliyun-oss-deploy

🙈 一个 nodejs 命令行工具,用于部署静态资源到 aliyun oss,支持代码方式和 CLI 方式!
JavaScript
35
star
30

slice.js

🌌 nano library to enhance String.substring / Array.slice with python slice style by Proxy.
JavaScript
34
star
31

hint

重构到 ---> https://github.com/hustcc/lint-md
Python
34
star
32

G2Plot-QRCode

Draw a QRCode with G2Plot.
TypeScript
33
star
33

tplv

👣 Nano string template library for modern, based on ES6 template string syntax.
TypeScript
33
star
34

post-messenger

👶 ~1 Kb wrapper of window.postMessage for cross-document communication.
JavaScript
28
star
35

filesize.js

🔥 filesize.js is a simple(~360 b) module to make file size human-readable.
TypeScript
26
star
36

variable-type

👏 ~ 1 kb. Schema validation. 一个只有 1 kb 的用于变量结构校验的库。
TypeScript
24
star
37

hrn

🔢 Type module to format number into Human-Readable-String. e.g. 4567 -> 4.6 k.
JavaScript
23
star
38

miz

🎯 Generate fake data, Just like a person.
TypeScript
22
star
39

React-G2Plot

🤖 Unofficial react component wrapper for @antvis/G2Plot
TypeScript
21
star
40

return-top

Pure javascript achieve click image to return top of website with animation
JavaScript
19
star
41

xhr.js

🌎 xhr.js is a library(< 2Kb) to make AJAX/HTTP requests with XMLHttpRequest.
JavaScript
19
star
42

jchatting

Chat system developed by Java Swing & Java Socket. 使用Java Swing和Java Socket API实现的聊天系统。
Java
18
star
43

warpart

使用 Flask 做的一个唐诗展示网站。
Python
18
star
44

G2-50-Questions

❓ 500 Questions about G2.
16
star
45

diff-text

Just get the diff of a simple inline text, simple mode.
JavaScript
14
star
46

PrimeTable

Primes Table which Less then Ten million (10000000) 一千万以内的素数表(质数表)。
JavaScript
13
star
47

ding-robot

🤖 钉钉机器人 SDK for Node.js。
JavaScript
13
star
48

babel-plugin-optimize-i18n

🔑 优化国际化文案的 Babel 插件,可以减少国际化文案 40% ~ 50% 的 bundle size。
JavaScript
13
star
49

bmt

📏 in Browser, Measure Text width.
TypeScript
12
star
50

limit-size

🌤️ Lightweight, Convenient, Fast command tool to control your file size by CI, size-limit is too bloated.
TypeScript
11
star
51

uri-parse

🔗 Mini data-uri parser for nodejs and browser. No dependencies!
JavaScript
11
star
52

KeyHelper

😭 好怀念^_^ 基于 Java Swing 的一款键盘改键程序,初衷是用于 Dota 物品和英雄技能改键。
Java
11
star
53

horse.js

🐴 < 3Kb. autocomplete component of pure javascript. 纯Javascript实现的轻量简洁的提示组件。
JavaScript
11
star
54

g2-for-react

📈g2 在 React 上的简单组件包装。React component wrapper of @antvis g2.
JavaScript
11
star
55

clz

✍️ Serverless & Beautiful third-part comment system base on lean cloud.
TypeScript
11
star
56

yuque-lint

Markdown style lint service for Yuque.com base on webhook.
JavaScript
11
star
57

page-fps

🖼️ Inject fps indicator into your page for web performance.
TypeScript
8
star
58

byte-parser

8️⃣ (130B) Parse byte string to byte number, e.g. 1.2 Kb -> 1228.8, Kb, Mb, Gb, Tb, Pb, Eb, Zb, Yb supported.
TypeScript
7
star
59

immutability-util

🌿 Mutate a copy of data without changing the original source by path string, just like the get/set in lodash. Inspired by immutability-helper and rewrite with ES6.
JavaScript
7
star
60

radix.js

💯 a simple javascript module to convent number to your radix, decimal supported.
JavaScript
6
star
61

npm-robbery

🚩 A command tool to register npm package name conveniently.
JavaScript
6
star
62

evenly

💦 How to divide the gold evenly? No surplus. 怎么均匀并且无遗漏的分配黄金?
JavaScript
6
star
63

TODO

📝 A simple github authorized application for server multi-user TODO list.
JavaScript
6
star
64

react-testing-demo

🏁 Ensure code quality of React components with jest, enzyme, jsdom, eslint.
JavaScript
5
star
65

jest-less-loader

⚛️ Jest transformer for .less file.
TypeScript
5
star
66

anyplot

🟪 Web Components for Visualization based on G2.
TypeScript
5
star
67

babel-plugin-version

🏷️ babel plugin replace define identifier `__VERSION__` to pkg.version!
JavaScript
5
star
68

rc-size-sensor

React component wrapper for DOM element size sensor.
TypeScript
4
star
69

charts-perf

Performance tests for charts library.
TypeScript
4
star
70

short-unique-string

🆎 Generate short unique id string locally, used optimize javascript code.
JavaScript
3
star
71

hustcc.github.io

Code for my GitHub profile.
HTML
3
star
72

chart-entanglement

模仿量子特效纠缠实现图表之间的联动。
JavaScript
3
star
73

what.js

👻 only 0.25 kb. what.js is a simple library to get the type of variables. enganced typeof function.
JavaScript
3
star
74

jest-url-loader

⚛️ Similar with webpack's url-loader for Jest.
TypeScript
3
star
75

browser-support-badge

Generate browser version compatibility badges
JavaScript
3
star
76

emoticon.js

{︶。︶}┛ simple javascript library to generate random text emoticon.
JavaScript
3
star
77

hustcc

2
star
78

the-git-commit

:octocat: Nano nodejs module to get information of any git commit.
JavaScript
2
star
79

inject-version

Inject version into your source code when prepublishOnly.
TypeScript
2
star
80

string-shorten

Shorten a string with crc32 and radix.
JavaScript
2
star
81

jest-expect

🃏😂 Make jest expect more convenient.
JavaScript
2
star
82

template

Repository template for @hustcc
JavaScript
1
star
83

pypi-demo

Just a simple pypi package code structure. You can use it to register pypi package name.
Python
1
star
84

gallery

Donate page.
CSS
1
star