jest-canvas-mock 2.2.0 → 2.4.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.
@@ -7,6 +7,35 @@ exports.default = void 0;
7
7
 
8
8
  function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
9
9
 
10
+ function sumMultipleOfMatricesCells(matrix1Array, matrix2Array, {
11
+ i,
12
+ j
13
+ }) {
14
+ let sum = 0;
15
+
16
+ for (let k = 0; k < 4; k++) {
17
+ const matrix1Index = j - 1 + k * 4;
18
+ const matrix2Index = (i - 1) * 4 + k;
19
+ sum += matrix1Array[matrix1Index] * matrix2Array[matrix2Index];
20
+ }
21
+
22
+ return sum;
23
+ }
24
+
25
+ function multiplyMatrices(leftMatrix, rightMatrix) {
26
+ const leftMatrixArray = leftMatrix.toFloat64Array();
27
+ const rightMatrixArray = rightMatrix.toFloat64Array();
28
+
29
+ for (let i = 1; i <= 4; i++) {
30
+ for (let j = 1; j <= 4; j++) {
31
+ leftMatrix[`m${i}${j}`] = sumMultipleOfMatricesCells(leftMatrixArray, rightMatrixArray, {
32
+ i,
33
+ j
34
+ });
35
+ }
36
+ }
37
+ }
38
+
10
39
  class DOMMatrix {
11
40
  constructor(transform) {
12
41
  _defineProperty(this, "_is2D", true);
@@ -76,7 +105,7 @@ class DOMMatrix {
76
105
  }
77
106
 
78
107
  if (transform) {
79
- throw new TypeError('Failed to construct \'DOMMatrix\': The sequence must contain 6 elements for a 2D matrix or 16 elements for a 3D matrix.');
108
+ throw new TypeError("Failed to construct 'DOMMatrix': The sequence must contain 6 elements for a 2D matrix or 16 elements for a 3D matrix.");
80
109
  }
81
110
 
82
111
  this._is2D = false;
@@ -142,6 +171,77 @@ class DOMMatrix {
142
171
  return this._is2D;
143
172
  }
144
173
 
174
+ toFloat32Array() {
175
+ return new Float32Array([this.m11, this.m12, this.m13, this.m14, this.m21, this.m22, this.m23, this.m24, this.m31, this.m32, this.m33, this.m34, this.m41, this.m42, this.m43, this.m44]);
176
+ }
177
+
178
+ toFloat64Array() {
179
+ return new Float64Array([this.m11, this.m12, this.m13, this.m14, this.m21, this.m22, this.m23, this.m24, this.m31, this.m32, this.m33, this.m34, this.m41, this.m42, this.m43, this.m44]);
180
+ }
181
+
182
+ translateSelf(x, y, z) {
183
+ const tx = Number(x),
184
+ ty = Number(y),
185
+ tz = isNaN(Number(z)) ? 0 : Number(z);
186
+ const translationMatrix = new DOMMatrix();
187
+ translationMatrix.m41 = tx;
188
+ translationMatrix.m42 = ty;
189
+ translationMatrix.m43 = tz;
190
+ multiplyMatrices(this, translationMatrix);
191
+
192
+ if (tz) {
193
+ this._is2D = false;
194
+ }
195
+
196
+ return this;
197
+ }
198
+
199
+ translate(x, y, z) {
200
+ let translatedMatrix;
201
+
202
+ if (this.is2D) {
203
+ translatedMatrix = new DOMMatrix([this.a, this.b, this.c, this.d, this.e, this.f]);
204
+ } else {
205
+ translatedMatrix = new DOMMatrix(this.toFloat32Array());
206
+ }
207
+
208
+ return translatedMatrix.translateSelf(x, y, z);
209
+ }
210
+
211
+ scaleSelf(scaleX, scaleY, scaleZ, originX, originY, originZ) {
212
+ const sx = Number(scaleX),
213
+ sy = isNaN(Number(scaleY)) ? sx : Number(scaleY),
214
+ sz = isNaN(Number(scaleZ)) ? 1 : Number(scaleZ);
215
+ const ox = isNaN(Number(originX)) ? 0 : Number(originX),
216
+ oy = isNaN(Number(originY)) ? 0 : Number(originY),
217
+ oz = isNaN(Number(originZ)) ? 0 : Number(originZ);
218
+ this.translateSelf(ox, oy, oz);
219
+ const scaleMatrix = new DOMMatrix();
220
+ scaleMatrix.m11 = sx;
221
+ scaleMatrix.m22 = sy;
222
+ scaleMatrix.m33 = sz;
223
+ multiplyMatrices(this, scaleMatrix);
224
+ this.translateSelf(-ox, -oy, -oz);
225
+
226
+ if (Math.abs(sz) !== 1) {
227
+ this._is2D = false;
228
+ }
229
+
230
+ return this;
231
+ }
232
+
233
+ scale(scaleX, scaleY, scaleZ, originX, originY, originZ) {
234
+ let scaledMatrix;
235
+
236
+ if (this.is2D) {
237
+ scaledMatrix = new DOMMatrix([this.a, this.b, this.c, this.d, this.e, this.f]);
238
+ } else {
239
+ scaledMatrix = new DOMMatrix(this.toFloat32Array());
240
+ }
241
+
242
+ return scaledMatrix.scaleSelf(scaleX, scaleY, scaleZ, originX, originY, originZ);
243
+ }
244
+
145
245
  }
146
246
 
147
247
  exports.default = DOMMatrix;
@@ -55,7 +55,7 @@ class ImageData {
55
55
  if (h === 0) throw new RangeError('The height is zero or not a number.');
56
56
  if (!Number.isFinite(w)) throw new RangeError('The width is zero or not a number.');
57
57
  if (w === 0) throw new RangeError('The width is zero or not a number.');
58
- if (arr.length !== w * h * 4) throw new RangeError('Source doesn\'n contain the exact number of pixels needed.');
58
+ if (arr.length !== w * h * 4) throw new RangeError("Source doesn'n contain the exact number of pixels needed.");
59
59
  this._width = w;
60
60
  this._height = h;
61
61
  this._data = arr;
@@ -34,9 +34,10 @@ class Path2D {
34
34
  }
35
35
 
36
36
  addPath(path) {
37
- if (arguments.length < 1) throw new TypeError('Failed to execute \'addPath\' on \'Path2D\': 1 argument required, but only 0 present.');
38
- if (!(path instanceof Path2D)) throw new TypeError('Failed to execute \'addPath\' on \'Path2D\': parameter 1 is not of type \'Path2D\'.');
39
- this._path = this._path.concat(path._path);
37
+ if (arguments.length < 1) throw new TypeError("Failed to execute 'addPath' on 'Path2D': 1 argument required, but only 0 present.");
38
+ if (!(path instanceof Path2D)) throw new TypeError("Failed to execute 'addPath' on 'Path2D': parameter 1 is not of type 'Path2D'.");
39
+
40
+ for (let i = 0; i < path._path.length; i++) this._path.push(path._path[i]);
40
41
  }
41
42
 
42
43
  }
package/lib/index.js CHANGED
@@ -9,15 +9,15 @@ var _window = _interopRequireDefault(require("./window"));
9
9
 
10
10
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
11
11
 
12
- /**
13
- * Created by hustcc 17/12/25.
14
- * Contract: i@hust.cc
12
+ /**
13
+ * Created by hustcc 17/12/25.
14
+ * Contract: i@hust.cc
15
15
  */
16
16
  // mock global window
17
17
  // TODO: Force coverage to ignore this branch
18
18
  if (typeof window !== 'undefined') {
19
- global.window = (0, _window.default)(window);
19
+ (0, _window.default)(global.window);
20
20
  }
21
21
 
22
- const ver = "2.2.0";
22
+ const ver = "2.4.0";
23
23
  exports.ver = ver;
@@ -5,20 +5,20 @@ Object.defineProperty(exports, "__esModule", {
5
5
  });
6
6
  exports.default = createCanvasEvent;
7
7
 
8
- /**
9
- * This function returns a CanvasRenderingContext2DEvent. Whenever an operation would modify the canvas
10
- * context, this function should be used to generate an "event" that represents that sort of modification.
11
- * This will be used to mock for snapshots.
12
- *
13
- * @example
14
- * interface CanvasRenderingContext2DEvent {
15
- * type: string;
16
- * transform: [number, number, number, number, number, number]; // the resulting current transform
17
- * props: {
18
- * // if the event is a property was set, `event.props.value` would be set
19
- * [propName: string]: any;
20
- * };
21
- * }
8
+ /**
9
+ * This function returns a CanvasRenderingContext2DEvent. Whenever an operation would modify the canvas
10
+ * context, this function should be used to generate an "event" that represents that sort of modification.
11
+ * This will be used to mock for snapshots.
12
+ *
13
+ * @example
14
+ * interface CanvasRenderingContext2DEvent {
15
+ * type: string;
16
+ * transform: [number, number, number, number, number, number]; // the resulting current transform
17
+ * props: {
18
+ * // if the event is a property was set, `event.props.value` would be set
19
+ * [propName: string]: any;
20
+ * };
21
+ * }
22
22
  */
23
23
  function createCanvasEvent(type, transform, props) {
24
24
  return {
@@ -12,17 +12,17 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de
12
12
  var _default = jest.fn(function createImageBitmap(img, sx, sy, sWidth, sHeight, options) {
13
13
  var length = arguments.length;
14
14
  return new Promise((resolve, reject) => {
15
- if (length === 0) return reject(new TypeError('Failed to execute \'createImageBitmap\' on \'Window\': 1 argument required, but only 0 present.'));
16
- if (length === 3 || length === 4) return reject(new TypeError('Failed to execute \'createImageBitmap\' on \'Window\': Valid arities are: [1, 2, 5, 6], but ' + length + ' arguments provided.'));
15
+ if (length === 0) return reject(new TypeError("Failed to execute 'createImageBitmap' on 'Window': 1 argument required, but only 0 present."));
16
+ if (length === 3 || length === 4) return reject(new TypeError("Failed to execute 'createImageBitmap' on 'Window': Valid arities are: [1, 2, 5, 6], but " + length + ' arguments provided.'));
17
17
  let validImage = false;
18
18
  if (img instanceof HTMLImageElement) validImage = true;
19
19
  if (img instanceof HTMLVideoElement) validImage = true;
20
20
  if (img instanceof HTMLCanvasElement) validImage = true; // checking constructor name is the only reliable way to verify the object's constructing class is "blob-like"
21
21
 
22
- if (img instanceof Blob || img && img.constructor && img.constructor.name === "Blob") validImage = true;
22
+ if (img instanceof Blob || img && img.constructor && img.constructor.name === 'Blob') validImage = true;
23
23
  if (img instanceof _ImageBitmap.default) validImage = true;
24
24
  if (img instanceof ImageData) validImage = true;
25
- if (!validImage) return reject(new TypeError('Failed to execute \'createImageBitmap\' on \'Window\': The provided value is not of type \'(HTMLImageElement or SVGImageElement or HTMLVideoElement or HTMLCanvasElement or Blob or ImageData or ImageBitmap or OffscreenCanvas)\''));
25
+ if (!validImage) return reject(new TypeError("Failed to execute 'createImageBitmap' on 'Window': The provided value is not of type '(HTMLImageElement or SVGImageElement or HTMLVideoElement or HTMLCanvasElement or Blob or ImageData or ImageBitmap or OffscreenCanvas)'"));
26
26
 
27
27
  if (length >= 2) {
28
28
  let index = 6;
@@ -35,7 +35,7 @@ var _default = jest.fn(function createImageBitmap(img, sx, sy, sWidth, sHeight,
35
35
  if (length === 5) options = null;
36
36
 
37
37
  if (options !== null && options !== void 0) {
38
- if (typeof options !== 'object') throw new TypeError('Failed to execute \'createImageBitmap\' on \'Window\': parameter ' + index + ' (\'options\') is not an object.');
38
+ if (typeof options !== 'object') throw new TypeError("Failed to execute 'createImageBitmap' on 'Window': parameter " + index + " ('options') is not an object.");
39
39
  }
40
40
  }
41
41
 
@@ -6,23 +6,23 @@ Object.defineProperty(exports, "__esModule", {
6
6
  exports.default = mockPrototype;
7
7
 
8
8
  function mockPrototype() {
9
- /**
10
- * This weakmap is designed to contain all of the generated canvas contexts. It's keys are the
11
- * jsdom canvases obtained by using the `this` keyword inside the `#getContext('2d')` function
12
- * call. It's values are the generated `CanvasRenderingContext2D` objects.
9
+ /**
10
+ * This weakmap is designed to contain all of the generated canvas contexts. It's keys are the
11
+ * jsdom canvases obtained by using the `this` keyword inside the `#getContext('2d')` function
12
+ * call. It's values are the generated `CanvasRenderingContext2D` objects.
13
13
  */
14
14
  const generatedContexts = new WeakMap();
15
- /**
16
- * Overrides getContext. Every test run will create a new function that overrides the current
17
- * value of getContext. It attempts to preserve the original getContext function by storing it on
18
- * the callback as a property.
15
+ /**
16
+ * Overrides getContext. Every test run will create a new function that overrides the current
17
+ * value of getContext. It attempts to preserve the original getContext function by storing it on
18
+ * the callback as a property.
19
19
  */
20
20
 
21
21
  const getContext2D = jest.fn(function getContext2d(type) {
22
22
  if (type === '2d') {
23
- /**
24
- * Contexts must be indempotent. Once they are generated, they should be returned when
25
- * getContext() is called on the same canvas object multiple times.
23
+ /**
24
+ * Contexts must be indempotent. Once they are generated, they should be returned when
25
+ * getContext() is called on the same canvas object multiple times.
26
26
  */
27
27
  if (generatedContexts.has(this)) return generatedContexts.get(this);
28
28
  const ctx = new CanvasRenderingContext2D(this);
@@ -46,17 +46,17 @@ function mockPrototype() {
46
46
  }
47
47
 
48
48
  HTMLCanvasElement.prototype.getContext = getContext2D;
49
- /**
50
- * This function technically throws SecurityError at runtime, but it cannot be mocked, because
51
- * we don't know if the canvas is tainted. These kinds of errors will be silent.
49
+ /**
50
+ * This function technically throws SecurityError at runtime, but it cannot be mocked, because
51
+ * we don't know if the canvas is tainted. These kinds of errors will be silent.
52
52
  */
53
53
 
54
54
  const toBlobOverride = jest.fn(function toBlobOverride(callback, mimetype) {
55
- if (arguments.length < 1) throw new TypeError('Failed to execute \'toBlob\' on \'HTMLCanvasElement\': 1 argument required, but only 0 present.');
56
- if (typeof callback !== 'function') throw new TypeError('Failed to execute \'toBlob\' on \'HTMLCanvasElement\': The callback provided as parameter 1 is not a function.');
57
- /**
58
- * Mime type must be image/jpeg or image/webp exactly for the browser to accept it, otherwise
59
- * it's image/png.
55
+ if (arguments.length < 1) throw new TypeError("Failed to execute 'toBlob' on 'HTMLCanvasElement': 1 argument required, but only 0 present.");
56
+ if (typeof callback !== 'function') throw new TypeError("Failed to execute 'toBlob' on 'HTMLCanvasElement': The callback provided as parameter 1 is not a function.");
57
+ /**
58
+ * Mime type must be image/jpeg or image/webp exactly for the browser to accept it, otherwise
59
+ * it's image/png.
60
60
  */
61
61
 
62
62
  switch (mimetype) {
@@ -69,9 +69,9 @@ function mockPrototype() {
69
69
  default:
70
70
  mimetype = 'image/png';
71
71
  }
72
- /**
73
- * This section creates a blob of size width * height * 4. This is not actually valid, because
74
- * jpeg size is variable, and so is png. TODO: Is there a better way to do this?
72
+ /**
73
+ * This section creates a blob of size width * height * 4. This is not actually valid, because
74
+ * jpeg size is variable, and so is png. TODO: Is there a better way to do this?
75
75
  */
76
76
 
77
77
 
@@ -90,9 +90,9 @@ function mockPrototype() {
90
90
  }
91
91
 
92
92
  HTMLCanvasElement.prototype.toBlob = toBlobOverride;
93
- /**
94
- * This section creates a dataurl with a validated mime type. This is not actually valid, because
95
- * jpeg size is variable, and so is png. TODO: Is there a better way to do this?
93
+ /**
94
+ * This section creates a dataurl with a validated mime type. This is not actually valid, because
95
+ * jpeg size is variable, and so is png. TODO: Is there a better way to do this?
96
96
  */
97
97
 
98
98
  const toDataURLOverride = jest.fn(function toDataURLOverride(type, encoderOptions) {
@@ -106,8 +106,8 @@ function mockPrototype() {
106
106
  default:
107
107
  type = 'image/png';
108
108
  }
109
- /**
110
- * This is the smallest valid data url I could generate.
109
+ /**
110
+ * This is the smallest valid data url I could generate.
111
111
  */
112
112
 
113
113
 
package/lib/window.js CHANGED
@@ -27,9 +27,9 @@ var _createImageBitmap = _interopRequireDefault(require("./mock/createImageBitma
27
27
 
28
28
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
29
29
 
30
- /**
31
- * Created by hustcc 17/12/25.
32
- * Contract: i@hust.cc
30
+ /**
31
+ * Created by hustcc 17/12/25.
32
+ * Contract: i@hust.cc
33
33
  */
34
34
  var _default = win => {
35
35
  const d = win.document;
@@ -54,10 +54,10 @@ var _default = win => {
54
54
  // if ctx not exist, mock it.
55
55
  // just mock canvas creator.
56
56
 
57
- /*
58
- win.document.createElement = param => param.toString().toLowerCase() === 'canvas'
59
- ? createCanvas('canvas')
60
- : f.call(d, param);
57
+ /*
58
+ win.document.createElement = param => param.toString().toLowerCase() === 'canvas'
59
+ ? createCanvas('canvas')
60
+ : f.call(d, param);
61
61
  */
62
62
  // if not exist, then mock it.
63
63
 
package/package.json CHANGED
@@ -1,70 +1,79 @@
1
- {
2
- "name": "jest-canvas-mock",
3
- "version": "2.2.0",
4
- "description": "Mock a canvas in your jest tests.",
5
- "main": "lib/index.js",
6
- "types": "types/index.d.ts",
7
- "scripts": {
8
- "test": "jest --no-cache",
9
- "build": "babel src --out-dir lib",
10
- "coveralls": "cat ./coverage/lcov.info | coveralls",
11
- "prepare": "npm run build"
12
- },
13
- "dependencies": {
14
- "cssfontparser": "^1.2.1",
15
- "parse-color": "^1.0.0"
16
- },
17
- "devDependencies": {
18
- "@babel/cli": "^7.6.4",
19
- "@babel/core": "^7.6.4",
20
- "@babel/plugin-proposal-class-properties": "^7.5.5",
21
- "@babel/preset-env": "^7.6.3",
22
- "@commitlint/cli": "^8.2.0",
23
- "@commitlint/config-angular": "^8.2.0",
24
- "babel-jest": "^24.9.0",
25
- "babel-plugin-version": "^0.2.3",
26
- "coveralls": "^3.0.7",
27
- "husky": "^3.0.9",
28
- "jest": "^24.9.0"
29
- },
30
- "commitlint": {
31
- "extends": [
32
- "@commitlint/config-angular"
33
- ]
34
- },
35
- "husky": {
36
- "hooks": {
37
- "commit-msg": "commitlint -E HUSKY_GIT_PARAMS",
38
- "pre-commit": "npm run test && npm run build"
39
- }
40
- },
41
- "jest": {
42
- "collectCoverage": true,
43
- "collectCoverageFrom": [
44
- "src/classes/**/*.js",
45
- "src/mock/**/*.js"
46
- ],
47
- "setupFiles": [
48
- "./src/index.js"
49
- ]
50
- },
51
- "repository": {
52
- "type": "git",
53
- "url": "git+https://github.com/hustcc/jest-canvas-mock.git"
54
- },
55
- "keywords": [
56
- "mock",
57
- "jest",
58
- "jest-mock",
59
- "echarts",
60
- "canvas",
61
- "test",
62
- "unit"
63
- ],
64
- "author": "hustcc",
65
- "license": "MIT",
66
- "bugs": {
67
- "url": "https://github.com/hustcc/jest-canvas-mock/issues"
68
- },
69
- "homepage": "https://github.com/hustcc/jest-canvas-mock#readme"
70
- }
1
+ {
2
+ "name": "jest-canvas-mock",
3
+ "version": "2.4.0",
4
+ "description": "Mock a canvas in your jest tests.",
5
+ "main": "lib/index.js",
6
+ "types": "types/index.d.ts",
7
+ "scripts": {
8
+ "test": "jest --no-cache",
9
+ "build": "babel src --out-dir lib",
10
+ "coveralls": "cat ./coverage/lcov.info | coveralls",
11
+ "prepare": "npm run build",
12
+ "prettier": "prettier --write ."
13
+ },
14
+ "dependencies": {
15
+ "cssfontparser": "^1.2.1",
16
+ "moo-color": "^1.0.2"
17
+ },
18
+ "devDependencies": {
19
+ "@antv/g2plot": "^2.3.11",
20
+ "@babel/cli": "^7.8.4",
21
+ "@babel/core": "^7.9.0",
22
+ "@babel/plugin-proposal-class-properties": "^7.8.3",
23
+ "@babel/preset-env": "^7.9.5",
24
+ "@commitlint/cli": "^8.3.5",
25
+ "@commitlint/config-angular": "^8.3.4",
26
+ "babel-jest": "^25.3.0",
27
+ "babel-plugin-version": "^0.2.3",
28
+ "coveralls": "^3.0.11",
29
+ "husky": "^4.2.5",
30
+ "jest": "^25.3.0",
31
+ "prettier": "^2.0.4"
32
+ },
33
+ "commitlint": {
34
+ "extends": [
35
+ "@commitlint/config-angular"
36
+ ]
37
+ },
38
+ "husky": {
39
+ "hooks": {
40
+ "commit-msg": "commitlint -E HUSKY_GIT_PARAMS",
41
+ "pre-commit": "npm run prettier && npm run test && npm run build"
42
+ }
43
+ },
44
+ "jest": {
45
+ "collectCoverage": true,
46
+ "collectCoverageFrom": [
47
+ "src/classes/**/*.js",
48
+ "src/mock/**/*.js"
49
+ ],
50
+ "setupFiles": [
51
+ "./src/index.js",
52
+ "./__mocks__/worker.js"
53
+ ]
54
+ },
55
+ "repository": {
56
+ "type": "git",
57
+ "url": "git+https://github.com/hustcc/jest-canvas-mock.git"
58
+ },
59
+ "keywords": [
60
+ "mock",
61
+ "jest",
62
+ "jest-mock",
63
+ "echarts",
64
+ "canvas",
65
+ "test",
66
+ "unit"
67
+ ],
68
+ "files": [
69
+ "CHANGELOG.md",
70
+ "lib/",
71
+ "types/"
72
+ ],
73
+ "author": "hustcc",
74
+ "license": "MIT",
75
+ "bugs": {
76
+ "url": "https://github.com/hustcc/jest-canvas-mock/issues"
77
+ },
78
+ "homepage": "https://github.com/hustcc/jest-canvas-mock#readme"
79
+ }