jest-canvas-mock 2.2.0 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,169 +1,185 @@
1
- # jest-canvas-mock
2
-
3
- > Mock `canvas` when run unit test cases with jest. For more browser environment, you can use [jest-electron](https://github.com/hustcc/jest-electron) for real browser runtime.
4
-
5
- [![Build Status](https://travis-ci.org/hustcc/jest-canvas-mock.svg?branch=master)](https://travis-ci.org/hustcc/jest-canvas-mock)
6
- [![Coverage Status](https://coveralls.io/repos/github/hustcc/jest-canvas-mock/badge.svg?branch=master)](https://coveralls.io/github/hustcc/jest-canvas-mock)
7
- [![npm](https://img.shields.io/npm/v/jest-canvas-mock.svg)](https://www.npmjs.com/package/jest-canvas-mock)
8
- [![npm](https://img.shields.io/npm/dm/jest-canvas-mock.svg)](https://www.npmjs.com/package/jest-canvas-mock)
9
-
10
-
11
- ## Install
12
-
13
- This should only be installed as a development dependency (`devDependencies`) as it is only designed for testing.
14
-
15
- ```bash
16
- npm i --save-dev jest-canvas-mock
17
- ```
18
-
19
-
20
- ## Setup
21
-
22
- In your `package.json` under the `jest`, create a `setupFiles` array and add `jest-canvas-mock` to the array.
23
-
24
- ```json
25
- {
26
- "jest": {
27
- "setupFiles": ["jest-canvas-mock"]
28
- }
29
- }
30
- ```
31
-
32
- If you already have a `setupFiles` attribute you can also append `jest-canvas-mock` to the array.
33
-
34
- ```json
35
- {
36
- "jest": {
37
- "setupFiles": ["./__setups__/other.js", "jest-canvas-mock"]
38
- }
39
- }
40
- ```
41
-
42
- More about in [configuration section](https://facebook.github.io/jest/docs/en/configuration.html#content).
43
-
44
-
45
- ## Setup file
46
-
47
- Alternatively you can create a new setup file which then requires this module or
48
- add the `require` statement to an existing setup file.
49
-
50
- `__setups__/canvas.js`
51
-
52
- ```js
53
- import 'jest-canvas-mock';
54
- // or
55
- require('jest-canvas-mock');
56
- ```
57
-
58
- Add that file to your `setupFiles` array:
59
-
60
- ```json
61
- "jest": {
62
- "setupFiles": [
63
- "./__setups__/canvas.js"
64
- ]
65
- }
66
- ```
67
-
68
- ## Mock Strategy
69
-
70
- This mock strategy implements all the canvas functions and actually verifies the parameters. If a
71
- known condition would cause the browser to throw a `TypeError` or a `DOMException`, it emulates the
72
- error. For instance, the `CanvasRenderingContext2D#arc` function will throw a `TypeError` if the
73
- radius is negative, or if it was not provided with enough parameters.
74
-
75
- ```ts
76
- // arc throws a TypeError when the argument length is less than 5
77
- expect(() => ctx.arc(1, 2, 3, 4)).toThrow(TypeError);
78
-
79
- // when radius is negative, arc throws a dom exception when all parameters are finite
80
- expect(() => ctx.arc(0, 0, -10, 0, Math.PI * 2)).toThrow(DOMException);
81
- ```
82
-
83
- The function will do `Number` type coercion and verify the inputs exactly like the browser does. So
84
- this is valid input.
85
-
86
- ```ts
87
- expect(() => ctx.arc("10", "10", "20", "0", "6.14")).not.toThrow();
88
- ```
89
-
90
- Another part of the strategy is to validate input types. When using the
91
- `CanvasRenderingContext2D#fill` function, if you pass it an invalid `fillRule` it will throw a
92
- `TypeError` just like the browser does.
93
-
94
- ```ts
95
- expect(() => ctx.fill("invalid!")).toThrow(TypeError);
96
- expect(() => ctx.fill(new Path2D(), "invalid!")).toThrow(TypeError);
97
- ```
98
-
99
- We try to follow the ECMAScript specification as closely as possible.
100
-
101
- # Snapshots
102
-
103
- There are multiple ways to validate canvas state. There are currently three `static` methods attached
104
- to the `CanvasRenderingContext2D` class. The first way to use this feature is by using the `__getEvents`
105
- method.
106
-
107
- ```ts
108
- /**
109
- * In order to see which functions and properties were used for the test, you can use `__getEvents`
110
- * to gather this information.
111
- */
112
- const events = ctx.__getEvents();
113
-
114
- expect(events).toMatchSnapshot(); // jest will assert the events match the snapshot
115
- ```
116
-
117
- The second way is to inspect the current path associated with the context.
118
-
119
- ```ts
120
- ctx.beginPath();
121
- ctx.arc(1, 2, 3, 4, 5);
122
- ctx.moveTo(6, 7);
123
- ctx.rect(6, 7, 8, 9);
124
- ctx.closePath();
125
-
126
- /**
127
- * Any method that modifies the current path (and subpath) will be pushed to an event array. When
128
- * using the `__getPath` method, that array will sliced and usable for snapshots.
129
- */
130
- const path = ctx.__getPath();
131
- expect(path).toMatchSnapshot();
132
- ```
133
-
134
- The third way is to inspect all of the success draw calls submitted to the context.
135
-
136
- ```ts
137
- ctx.drawImage(img, 0, 0);
138
-
139
- /**
140
- * Every drawImage, fill, stroke, fillText, or strokeText function call will be logged in an event
141
- * array. This method will return those events here for inspection.
142
- */
143
- const calls = ctx.__getDrawCalls();
144
- expect(calls).toMatchSnapshot();
145
- ```
146
-
147
- In some cases it may be useful to clear the events or draw calls that have already been logged.
148
-
149
- ```ts
150
- // Clear events
151
- ctx.__clearEvents();
152
-
153
- // Clear draw calls
154
- ctx.__clearDrawCalls();
155
- ```
156
-
157
- ## Override default mock return value
158
-
159
- You can override the default mock return value in your test to suit your need. For example, to override return value of `toDataURL`:
160
-
161
- ```ts
162
- canvas.toDataURL.mockReturnValueOnce(
163
- 'data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='
164
- );
165
- ```
166
-
167
- ## License
168
-
169
- MIT@[hustcc](https://github.com/hustcc).
1
+ # jest-canvas-mock
2
+
3
+ > Mock `canvas` when run unit test cases with jest. For more browser environment, you can use [jest-electron](https://github.com/hustcc/jest-electron) for real browser runtime.
4
+
5
+ [![Build Status](https://travis-ci.org/hustcc/jest-canvas-mock.svg?branch=master)](https://travis-ci.org/hustcc/jest-canvas-mock)
6
+ [![Coverage Status](https://coveralls.io/repos/github/hustcc/jest-canvas-mock/badge.svg?branch=master)](https://coveralls.io/github/hustcc/jest-canvas-mock)
7
+ [![npm](https://img.shields.io/npm/v/jest-canvas-mock.svg)](https://www.npmjs.com/package/jest-canvas-mock)
8
+ [![npm](https://img.shields.io/npm/dm/jest-canvas-mock.svg)](https://www.npmjs.com/package/jest-canvas-mock)
9
+ [![Mentioned in Awesome Jest](https://awesome.re/mentioned-badge.svg)](https://github.com/jest-community/awesome-jest)
10
+
11
+ ## Install
12
+
13
+ This should only be installed as a development dependency (`devDependencies`) as it is only designed for testing.
14
+
15
+ ```bash
16
+ npm i --save-dev jest-canvas-mock
17
+ ```
18
+
19
+ ## Setup
20
+
21
+ In your `package.json` under the `jest`, create a `setupFiles` array and add `jest-canvas-mock` to the array.
22
+
23
+ ```json
24
+ {
25
+ "jest": {
26
+ "setupFiles": ["jest-canvas-mock"]
27
+ }
28
+ }
29
+ ```
30
+
31
+ If you already have a `setupFiles` attribute you can also append `jest-canvas-mock` to the array.
32
+
33
+ ```json
34
+ {
35
+ "jest": {
36
+ "setupFiles": ["./__setups__/other.js", "jest-canvas-mock"]
37
+ }
38
+ }
39
+ ```
40
+
41
+ More about in [configuration section](https://facebook.github.io/jest/docs/en/configuration.html#content).
42
+
43
+ ## Setup file
44
+
45
+ Alternatively you can create a new setup file which then requires this module or
46
+ add the `require` statement to an existing setup file.
47
+
48
+ `__setups__/canvas.js`
49
+
50
+ ```js
51
+ import 'jest-canvas-mock';
52
+ // or
53
+ require('jest-canvas-mock');
54
+ ```
55
+
56
+ Add that file to your `setupFiles` array:
57
+
58
+ ```json
59
+ "jest": {
60
+ "setupFiles": [
61
+ "./__setups__/canvas.js"
62
+ ]
63
+ }
64
+ ```
65
+
66
+ ## Mock Strategy
67
+
68
+ This mock strategy implements all the canvas functions and actually verifies the parameters. If a
69
+ known condition would cause the browser to throw a `TypeError` or a `DOMException`, it emulates the
70
+ error. For instance, the `CanvasRenderingContext2D#arc` function will throw a `TypeError` if the
71
+ radius is negative, or if it was not provided with enough parameters.
72
+
73
+ ```ts
74
+ // arc throws a TypeError when the argument length is less than 5
75
+ expect(() => ctx.arc(1, 2, 3, 4)).toThrow(TypeError);
76
+
77
+ // when radius is negative, arc throws a dom exception when all parameters are finite
78
+ expect(() => ctx.arc(0, 0, -10, 0, Math.PI * 2)).toThrow(DOMException);
79
+ ```
80
+
81
+ The function will do `Number` type coercion and verify the inputs exactly like the browser does. So
82
+ this is valid input.
83
+
84
+ ```ts
85
+ expect(() => ctx.arc('10', '10', '20', '0', '6.14')).not.toThrow();
86
+ ```
87
+
88
+ Another part of the strategy is to validate input types. When using the
89
+ `CanvasRenderingContext2D#fill` function, if you pass it an invalid `fillRule` it will throw a
90
+ `TypeError` just like the browser does.
91
+
92
+ ```ts
93
+ expect(() => ctx.fill('invalid!')).toThrow(TypeError);
94
+ expect(() => ctx.fill(new Path2D(), 'invalid!')).toThrow(TypeError);
95
+ ```
96
+
97
+ We try to follow the ECMAScript specification as closely as possible.
98
+
99
+ ## Snapshots
100
+
101
+ There are multiple ways to validate canvas state using snapshots. There are currently three methods
102
+ attached to the `CanvasRenderingContext2D` class. The first way to use this feature is by using the
103
+ `__getEvents` method.
104
+
105
+ ```ts
106
+ /**
107
+ * In order to see which functions and properties were used for the test, you can use `__getEvents`
108
+ * to gather this information.
109
+ */
110
+ const events = ctx.__getEvents();
111
+
112
+ expect(events).toMatchSnapshot(); // jest will assert the events match the snapshot
113
+ ```
114
+
115
+ The second way is to inspect the current path associated with the context.
116
+
117
+ ```ts
118
+ ctx.beginPath();
119
+ ctx.arc(1, 2, 3, 4, 5);
120
+ ctx.moveTo(6, 7);
121
+ ctx.rect(6, 7, 8, 9);
122
+ ctx.closePath();
123
+
124
+ /**
125
+ * Any method that modifies the current path (and subpath) will be pushed to an event array. When
126
+ * using the `__getPath` method, that array will sliced and usable for snapshots.
127
+ */
128
+ const path = ctx.__getPath();
129
+ expect(path).toMatchSnapshot();
130
+ ```
131
+
132
+ The third way is to inspect all of the successful draw calls submitted to the context.
133
+
134
+ ```ts
135
+ ctx.drawImage(img, 0, 0);
136
+
137
+ /**
138
+ * Every drawImage, fill, stroke, fillText, or strokeText function call will be logged in an event
139
+ * array. This method will return those events here for inspection.
140
+ */
141
+ const calls = ctx.__getDrawCalls();
142
+ expect(calls).toMatchSnapshot();
143
+ ```
144
+
145
+ In some cases it may be useful to clear the events or draw calls that have already been logged.
146
+
147
+ ```ts
148
+ // Clear events
149
+ ctx.__clearEvents();
150
+
151
+ // Clear draw calls
152
+ ctx.__clearDrawCalls();
153
+ ```
154
+
155
+ Finally, it's possible to inspect the clipping region calls by using the `__getClippingRegion`
156
+ function.
157
+
158
+ ```ts
159
+ const clippingRegion = ctx.__getClippingRegion();
160
+ expect(clippingRegion).toMatchSnapshot();
161
+ ```
162
+
163
+ The clipping region cannot be cleared because it's based on the stack values and when the `.clip()`
164
+ function is called.
165
+
166
+ ## Override default mock return value
167
+
168
+ You can override the default mock return value in your test to suit your need. For example, to override return value of `toDataURL`:
169
+
170
+ ```ts
171
+ canvas.toDataURL.mockReturnValueOnce(
172
+ 'data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='
173
+ );
174
+ ```
175
+
176
+ ## Contributors
177
+
178
+ - [@hustcc](https://github.com/hustcc)
179
+ - [@jtenner](https://github.com/jtenner)
180
+ - [@evanoc0](https://github.com/evanoc0)
181
+ - [@FeliciousX](https://github.com/FeliciousX)
182
+
183
+ ## License
184
+
185
+ MIT@[hustcc](https://github.com/hustcc).
@@ -5,9 +5,7 @@ Object.defineProperty(exports, "__esModule", {
5
5
  });
6
6
  exports.default = void 0;
7
7
 
8
- var _parseColor = _interopRequireDefault(require("parse-color"));
9
-
10
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
8
+ var _mooColor = require("moo-color");
11
9
 
12
10
  class CanvasGradient {
13
11
  constructor() {
@@ -16,16 +14,15 @@ class CanvasGradient {
16
14
 
17
15
  addColorStop(offset, color) {
18
16
  const numoffset = Number(offset);
19
- const colorstr = String(color);
20
17
 
21
18
  if (!Number.isFinite(numoffset) || numoffset < 0 || numoffset > 1) {
22
- throw new DOMException('IndexSizeError', 'Failed to execute \'addColorStop\' on \'CanvasGradient\': The provided value (\'' + numoffset + '\') is outside the range (0.0, 1.0)');
19
+ throw new DOMException('IndexSizeError', "Failed to execute 'addColorStop' on 'CanvasGradient': The provided value ('" + numoffset + "') is outside the range (0.0, 1.0)");
23
20
  }
24
21
 
25
- const output = (0, _parseColor.default)(colorstr);
26
-
27
- if (!output.hex) {
28
- throw new SyntaxError('Failed to execute \'addColorStop\' on \'CanvasGradient\': The value provided (\'' + color + '\') could not be parsed as a color.');
22
+ try {
23
+ new _mooColor.MooColor(color);
24
+ } catch (e) {
25
+ throw new SyntaxError("Failed to execute 'addColorStop' on 'CanvasGradient': The value provided ('" + color + "') could not be parsed as a color.");
29
26
  }
30
27
  }
31
28
 
@@ -11,7 +11,7 @@ class CanvasPattern {
11
11
  }
12
12
 
13
13
  setTransform(value) {
14
- if (arguments.length > 0 && !(value instanceof Object)) throw new TypeError('Failed to execute \'setTransform\' on \'CanvasPattern\': parameter 1 (\'transform\') is not an object.');
14
+ if (arguments.length > 0 && !(value instanceof Object)) throw new TypeError("Failed to execute 'setTransform' on 'CanvasPattern': parameter 1 ('transform') is not an object.");
15
15
  }
16
16
 
17
17
  }