chartjs-test-utils 0.4.0 → 1.0.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 +230 -4
- package/package.json +58 -22
- package/src/canvas.js +69 -0
- package/src/chart.js +241 -0
- package/src/context.js +171 -0
- package/src/fixtures.js +149 -0
- package/src/index.js +92 -0
- package/src/matchers.js +224 -0
- package/src/matchers.options.js +114 -0
- package/src/node.js +43 -0
- package/src/spriting.js +104 -0
- package/types/entry.d.ts +134 -0
- package/types/generated/canvas.d.ts +35 -0
- package/types/generated/chart.d.ts +93 -0
- package/types/generated/context.d.ts +49 -0
- package/types/generated/fixtures.d.ts +24 -0
- package/types/generated/index.d.ts +38 -0
- package/types/generated/matchers.d.ts +55 -0
- package/types/generated/matchers.options.d.ts +10 -0
- package/types/generated/node.d.ts +33 -0
- package/types/generated/spriting.d.ts +2 -0
- package/dist/chartjs-test-utils.js +0 -1178
package/src/context.js
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
// Code from https://stackoverflow.com/questions/4406864/html-canvas-unit-testing
|
|
2
|
+
|
|
3
|
+
// The 2d context methods the mock records. Module scope, and exported, so the
|
|
4
|
+
// declared surface in types/entry.d.ts can be checked against it -- see
|
|
5
|
+
// test/unit/context.test.js.
|
|
6
|
+
export const mockContextMethods = {
|
|
7
|
+
arc: () => {},
|
|
8
|
+
arcTo: () => {},
|
|
9
|
+
beginPath: () => {},
|
|
10
|
+
bezierCurveTo: () => {},
|
|
11
|
+
clearRect: () => {},
|
|
12
|
+
clip: () => {},
|
|
13
|
+
closePath: () => {},
|
|
14
|
+
fill: () => {},
|
|
15
|
+
fillRect: () => {},
|
|
16
|
+
fillText: () => {},
|
|
17
|
+
strokeText: () => {},
|
|
18
|
+
lineTo: () => {},
|
|
19
|
+
measureText: (text) => {
|
|
20
|
+
// return the number of characters * fixed size
|
|
21
|
+
// Uses fake numbers for the bounding box
|
|
22
|
+
return text
|
|
23
|
+
? {
|
|
24
|
+
actualBoundingBoxAscent: 4,
|
|
25
|
+
actualBoundingBoxDescent: 8,
|
|
26
|
+
actualBoundingBoxLeft: 15,
|
|
27
|
+
actualBoundingBoxRight: 25,
|
|
28
|
+
width: text.length * 10
|
|
29
|
+
}
|
|
30
|
+
: {
|
|
31
|
+
actualBoundingBoxAscent: 0,
|
|
32
|
+
actualBoundingBoxDescent: 0,
|
|
33
|
+
actualBoundingBoxLeft: 0,
|
|
34
|
+
actualBoundingBoxRight: 0,
|
|
35
|
+
width: 0
|
|
36
|
+
};
|
|
37
|
+
},
|
|
38
|
+
moveTo: () => {},
|
|
39
|
+
quadraticCurveTo: () => {},
|
|
40
|
+
rect: () => {},
|
|
41
|
+
restore: () => {},
|
|
42
|
+
rotate: () => {},
|
|
43
|
+
save: () => {},
|
|
44
|
+
setLineDash: () => {},
|
|
45
|
+
stroke: () => {},
|
|
46
|
+
strokeRect: () => {},
|
|
47
|
+
setTransform: () => {},
|
|
48
|
+
translate: () => {}
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
export default class Context {
|
|
52
|
+
constructor() {
|
|
53
|
+
this._calls = []; // names/args of recorded calls
|
|
54
|
+
this._initMethods();
|
|
55
|
+
|
|
56
|
+
this._fillStyle = null;
|
|
57
|
+
this._font = null;
|
|
58
|
+
this._lineCap = null;
|
|
59
|
+
this._lineDashOffset = null;
|
|
60
|
+
this._lineJoin = null;
|
|
61
|
+
this._lineWidth = null;
|
|
62
|
+
this._strokeStyle = null;
|
|
63
|
+
this._textAlign = null;
|
|
64
|
+
this._textBaseline = null;
|
|
65
|
+
|
|
66
|
+
// Define properties here so that we can record each time they are set
|
|
67
|
+
Object.defineProperties(this, {
|
|
68
|
+
fillStyle: {
|
|
69
|
+
get: function () {
|
|
70
|
+
return this._fillStyle;
|
|
71
|
+
},
|
|
72
|
+
set: function (style) {
|
|
73
|
+
this._fillStyle = style;
|
|
74
|
+
this.record('setFillStyle', [style]);
|
|
75
|
+
}
|
|
76
|
+
},
|
|
77
|
+
font: {
|
|
78
|
+
get: function () {
|
|
79
|
+
return this._font;
|
|
80
|
+
},
|
|
81
|
+
set: function (font) {
|
|
82
|
+
this._font = font;
|
|
83
|
+
this.record('setFont', [font]);
|
|
84
|
+
}
|
|
85
|
+
},
|
|
86
|
+
lineCap: {
|
|
87
|
+
get: function () {
|
|
88
|
+
return this._lineCap;
|
|
89
|
+
},
|
|
90
|
+
set: function (cap) {
|
|
91
|
+
this._lineCap = cap;
|
|
92
|
+
this.record('setLineCap', [cap]);
|
|
93
|
+
}
|
|
94
|
+
},
|
|
95
|
+
lineDashOffset: {
|
|
96
|
+
get: function () {
|
|
97
|
+
return this._lineDashOffset;
|
|
98
|
+
},
|
|
99
|
+
set: function (offset) {
|
|
100
|
+
this._lineDashOffset = offset;
|
|
101
|
+
this.record('setLineDashOffset', [offset]);
|
|
102
|
+
}
|
|
103
|
+
},
|
|
104
|
+
lineJoin: {
|
|
105
|
+
get: function () {
|
|
106
|
+
return this._lineJoin;
|
|
107
|
+
},
|
|
108
|
+
set: function (join) {
|
|
109
|
+
this._lineJoin = join;
|
|
110
|
+
this.record('setLineJoin', [join]);
|
|
111
|
+
}
|
|
112
|
+
},
|
|
113
|
+
lineWidth: {
|
|
114
|
+
get: function () {
|
|
115
|
+
return this._lineWidth;
|
|
116
|
+
},
|
|
117
|
+
set: function (width) {
|
|
118
|
+
this._lineWidth = width;
|
|
119
|
+
this.record('setLineWidth', [width]);
|
|
120
|
+
}
|
|
121
|
+
},
|
|
122
|
+
strokeStyle: {
|
|
123
|
+
get: function () {
|
|
124
|
+
return this._strokeStyle;
|
|
125
|
+
},
|
|
126
|
+
set: function (style) {
|
|
127
|
+
this._strokeStyle = style;
|
|
128
|
+
this.record('setStrokeStyle', [style]);
|
|
129
|
+
}
|
|
130
|
+
},
|
|
131
|
+
textAlign: {
|
|
132
|
+
get: function () {
|
|
133
|
+
return this._textAlign;
|
|
134
|
+
},
|
|
135
|
+
set: function (align) {
|
|
136
|
+
this._textAlign = align;
|
|
137
|
+
this.record('setTextAlign', [align]);
|
|
138
|
+
}
|
|
139
|
+
},
|
|
140
|
+
textBaseline: {
|
|
141
|
+
get: function () {
|
|
142
|
+
return this._textBaseline;
|
|
143
|
+
},
|
|
144
|
+
set: function (baseline) {
|
|
145
|
+
this._textBaseline = baseline;
|
|
146
|
+
this.record('setTextBaseline', [baseline]);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
_initMethods() {
|
|
152
|
+
Object.keys(mockContextMethods).forEach((name) => {
|
|
153
|
+
this[name] = (...args) => {
|
|
154
|
+
this.record(name, args);
|
|
155
|
+
return mockContextMethods[name].apply(this, args);
|
|
156
|
+
};
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
record(methodName, args) {
|
|
160
|
+
this._calls.push({
|
|
161
|
+
name: methodName,
|
|
162
|
+
args: Array.prototype.slice.call(args)
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
getCalls() {
|
|
166
|
+
return this._calls;
|
|
167
|
+
}
|
|
168
|
+
resetCalls() {
|
|
169
|
+
this._calls = [];
|
|
170
|
+
}
|
|
171
|
+
}
|
package/src/fixtures.js
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Fixture discovery for the pixel tests.
|
|
3
|
+
*
|
|
4
|
+
* Karma scanned `__karma__.files` and re-read every config through XHR. A
|
|
5
|
+
* bundler resolves the same files at build time instead -- but the glob has to
|
|
6
|
+
* stay in the consumer: `import.meta.glob` (and `require.context`) resolve
|
|
7
|
+
* against the file the literal pattern is written in, so the maps are passed in
|
|
8
|
+
* here rather than produced here.
|
|
9
|
+
*/
|
|
10
|
+
import {expect, it} from 'vitest';
|
|
11
|
+
import {readImageData} from './canvas.js';
|
|
12
|
+
import {acquireChart, releaseChart} from './chart.js';
|
|
13
|
+
import {toEqualImageData} from './matchers.js';
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Resolves the browser commands registered by the Vitest config.
|
|
17
|
+
*
|
|
18
|
+
* Imported lazily: `vitest/browser` throws outside browser mode, and the
|
|
19
|
+
* package entry has to stay importable from node -- `createMockContext` is used
|
|
20
|
+
* in node unit tests.
|
|
21
|
+
*/
|
|
22
|
+
async function browserCommands() {
|
|
23
|
+
const {server} = await import('vitest/browser');
|
|
24
|
+
return server.commands;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** `./fixtures/basic/labels.js` -> `basic/labels` */
|
|
28
|
+
function fixtureName(path, prefix) {
|
|
29
|
+
const name = path.startsWith(prefix) ? path.slice(prefix.length) : path;
|
|
30
|
+
return name.replace(/\.(js|json|png)$/, '');
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function collect(configs, images, prefix) {
|
|
34
|
+
const inputs = {};
|
|
35
|
+
const add = (path, key, value) => {
|
|
36
|
+
const name = fixtureName(path, prefix);
|
|
37
|
+
inputs[name] = inputs[name] || {};
|
|
38
|
+
inputs[name][key] = value;
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
for (const path of Object.keys(configs)) {
|
|
42
|
+
add(path, 'config', configs[path]);
|
|
43
|
+
}
|
|
44
|
+
for (const path of Object.keys(images)) {
|
|
45
|
+
add(path, 'png', images[path]);
|
|
46
|
+
}
|
|
47
|
+
return inputs;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function prepareConfig(name, json) {
|
|
51
|
+
const config = json.config;
|
|
52
|
+
config.options = config.options || {};
|
|
53
|
+
// plugins are disabled by default, except if the path contains 'plugin' or
|
|
54
|
+
// there are instance plugins
|
|
55
|
+
if (!name.includes('plugin') && config.plugins === undefined) {
|
|
56
|
+
config.options.plugins = config.options.plugins || false;
|
|
57
|
+
}
|
|
58
|
+
return config;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Asserts against the reference image, or rewrites it when updating.
|
|
63
|
+
*
|
|
64
|
+
* The update command exists only when the browser config registered it, so the
|
|
65
|
+
* normal suite cannot take this path by accident. Even then it rewrites only
|
|
66
|
+
* images that actually changed, so an update is a reviewable diff rather than
|
|
67
|
+
* every fixture touched.
|
|
68
|
+
*/
|
|
69
|
+
async function compareOrSave(chart, name, inputs, json, save) {
|
|
70
|
+
const expected = inputs.png ? await readImageData(inputs.png) : undefined;
|
|
71
|
+
|
|
72
|
+
if (!save) {
|
|
73
|
+
expect(chart).toEqualImageData(expected, json);
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
if (expected && toEqualImageData(chart, expected, json).pass) {
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
await save(name, chart.ctx.canvas.toDataURL());
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function specFromFixture(name, inputs) {
|
|
83
|
+
it(name, async (ctx) => {
|
|
84
|
+
const save = (await browserCommands()).saveFixtureImage;
|
|
85
|
+
const json = inputs.config;
|
|
86
|
+
if (!json) {
|
|
87
|
+
throw new Error(`Missing config file for fixture ${name}`);
|
|
88
|
+
}
|
|
89
|
+
if (!inputs.png && !save) {
|
|
90
|
+
throw new Error(`Missing PNG comparison file for fixture ${name}`);
|
|
91
|
+
}
|
|
92
|
+
json.description = json.description || name;
|
|
93
|
+
|
|
94
|
+
const chart = acquireChart(prepareConfig(name, json), json.options, ctx);
|
|
95
|
+
try {
|
|
96
|
+
const run = json.options?.run;
|
|
97
|
+
if (typeof run === 'function') {
|
|
98
|
+
await run(chart);
|
|
99
|
+
}
|
|
100
|
+
await compareOrSave(chart, name, inputs, json, save);
|
|
101
|
+
} finally {
|
|
102
|
+
releaseChart(chart);
|
|
103
|
+
}
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Builds the fixture spec generator from the maps the consumer globbed.
|
|
109
|
+
*
|
|
110
|
+
* @param {object} options
|
|
111
|
+
* @param {object} options.configs - map of path to fixture config (js and json)
|
|
112
|
+
* @param {object} options.images - map of path to reference image url
|
|
113
|
+
* @param {string} [options.prefix] - path prefix stripped from the fixture names
|
|
114
|
+
* @returns {function(string=): function} `specsFromFixtures(path)`
|
|
115
|
+
*
|
|
116
|
+
* @example
|
|
117
|
+
* export const specsFromFixtures = createFixtures({
|
|
118
|
+
* configs: {
|
|
119
|
+
* ...import.meta.glob('./fixtures/**\/*.js', {eager: true, import: 'default'}),
|
|
120
|
+
* ...import.meta.glob('./fixtures/**\/*.json', {eager: true, import: 'default'})
|
|
121
|
+
* },
|
|
122
|
+
* images: import.meta.glob('./fixtures/**\/*.png', {eager: true, import: 'default', query: '?url'}),
|
|
123
|
+
* prefix: './fixtures/'
|
|
124
|
+
* });
|
|
125
|
+
*/
|
|
126
|
+
export function createFixtures({configs, images, prefix = ''}) {
|
|
127
|
+
const fixtures = collect(configs, images, prefix);
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Returns a suite body registering one spec per fixture below `path`.
|
|
131
|
+
* @param {string} [path] - directory under the fixtures root, e.g. `basic`; omit for all
|
|
132
|
+
*/
|
|
133
|
+
function specsFromFixtures(path = '') {
|
|
134
|
+
const names = Object.keys(fixtures)
|
|
135
|
+
.filter((name) => path === '' || name.startsWith(`${path}/`))
|
|
136
|
+
.sort();
|
|
137
|
+
|
|
138
|
+
return () => {
|
|
139
|
+
if (names.length === 0) {
|
|
140
|
+
throw new Error(`No fixtures found under ${prefix}${path}`);
|
|
141
|
+
}
|
|
142
|
+
for (const name of names) {
|
|
143
|
+
specFromFixture(name, fixtures[name]);
|
|
144
|
+
}
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
return specsFromFixtures;
|
|
149
|
+
}
|
package/src/index.js
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import {afterEach, expect} from 'vitest';
|
|
2
|
+
import {injectCSS} from './canvas.js';
|
|
3
|
+
import {releaseCharts, useChart} from './chart.js';
|
|
4
|
+
import Context from './context.js';
|
|
5
|
+
import {matchers} from './matchers.js';
|
|
6
|
+
|
|
7
|
+
export {canvasFromImageData, createCanvas, createImageData, injectCSS, readImageData} from './canvas.js';
|
|
8
|
+
export {
|
|
9
|
+
acquireChart,
|
|
10
|
+
afterEvent,
|
|
11
|
+
buildChart,
|
|
12
|
+
destroyChart,
|
|
13
|
+
releaseChart,
|
|
14
|
+
releaseCharts,
|
|
15
|
+
triggerMouseEvent,
|
|
16
|
+
waitForResize
|
|
17
|
+
} from './chart.js';
|
|
18
|
+
export {createFixtures} from './fixtures.js';
|
|
19
|
+
export {
|
|
20
|
+
matchers,
|
|
21
|
+
toBeChartOfSize,
|
|
22
|
+
toBeCloseToPixel,
|
|
23
|
+
toBeCloseToPoint,
|
|
24
|
+
toBeValidChart,
|
|
25
|
+
toEqualImageData,
|
|
26
|
+
toEqualOneOf,
|
|
27
|
+
toEqualOptions
|
|
28
|
+
} from './matchers.js';
|
|
29
|
+
export {compareOptions} from './matchers.options.js';
|
|
30
|
+
export {spritingOff, spritingOn} from './spriting.js';
|
|
31
|
+
export {Context};
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* A 2d context that records the calls made to it, for tests that assert what a
|
|
35
|
+
* chart drew rather than how it looked. Works outside the browser.
|
|
36
|
+
* @returns {Context}
|
|
37
|
+
*/
|
|
38
|
+
export function createMockContext() {
|
|
39
|
+
return new Context();
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function injectWrapperCSS() {
|
|
43
|
+
// some style initialization to limit differences between browsers across different platforms.
|
|
44
|
+
injectCSS(
|
|
45
|
+
'.chartjs-wrapper, .chartjs-wrapper canvas {' +
|
|
46
|
+
'border: 0;' +
|
|
47
|
+
'margin: 0;' +
|
|
48
|
+
'padding: 0;' +
|
|
49
|
+
'}' +
|
|
50
|
+
'.chartjs-wrapper {' +
|
|
51
|
+
'position: absolute' +
|
|
52
|
+
'}'
|
|
53
|
+
);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Registers the matchers, the per-spec chart cleanup and the rendering defaults
|
|
58
|
+
* the reference images were captured with. Call it once, from a setup file.
|
|
59
|
+
*
|
|
60
|
+
* @param {object} options
|
|
61
|
+
* @param {typeof import('chart.js').Chart} options.Chart - the `Chart` export of chart.js. Injected
|
|
62
|
+
* rather than read from a global: Karma loaded the UMD bundle into `window`,
|
|
63
|
+
* a bundler does not.
|
|
64
|
+
* @param {number} [options.devicePixelRatio] - pinned to 1 by default, so the
|
|
65
|
+
* backing store matches the reference images whatever the display reports.
|
|
66
|
+
* @param {boolean} [options.wrapperCSS] - inject the chart wrapper stylesheet.
|
|
67
|
+
*
|
|
68
|
+
* @example
|
|
69
|
+
* import {Chart, registerables} from 'chart.js';
|
|
70
|
+
* import {setup} from 'chartjs-test-utils';
|
|
71
|
+
*
|
|
72
|
+
* Chart.register(...registerables);
|
|
73
|
+
* setup({Chart});
|
|
74
|
+
*/
|
|
75
|
+
export function setup({Chart, devicePixelRatio = 1, wrapperCSS = true} = {}) {
|
|
76
|
+
if (!Chart) {
|
|
77
|
+
throw new Error('setup() requires the Chart.js constructor: setup({Chart})');
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
useChart(Chart);
|
|
81
|
+
Chart.defaults.devicePixelRatio = devicePixelRatio;
|
|
82
|
+
|
|
83
|
+
if (wrapperCSS) {
|
|
84
|
+
injectWrapperCSS();
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
expect.extend(matchers);
|
|
88
|
+
|
|
89
|
+
afterEach(() => {
|
|
90
|
+
releaseCharts();
|
|
91
|
+
});
|
|
92
|
+
}
|
package/src/matchers.js
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Vitest matchers.
|
|
3
|
+
*
|
|
4
|
+
* Jasmine's `addMatchers` took factories returning a `compare` method; Vitest's
|
|
5
|
+
* `expect.extend` takes the comparison itself and wants a lazy `message`.
|
|
6
|
+
*/
|
|
7
|
+
import pixelmatch from 'pixelmatch';
|
|
8
|
+
import {canvasFromImageData, createImageData} from './canvas.js';
|
|
9
|
+
import {getChart} from './chart.js';
|
|
10
|
+
import {compareOptions} from './matchers.options.js';
|
|
11
|
+
|
|
12
|
+
const DEFAULT_THRESHOLD = 0.1;
|
|
13
|
+
const DEFAULT_TOLERANCE = 0.001;
|
|
14
|
+
|
|
15
|
+
function toPercent(value) {
|
|
16
|
+
return Math.round(value * 10000) / 100;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function resolveContext(actual) {
|
|
20
|
+
if (actual instanceof CanvasRenderingContext2D) {
|
|
21
|
+
return actual;
|
|
22
|
+
}
|
|
23
|
+
if (actual instanceof HTMLCanvasElement) {
|
|
24
|
+
return actual.getContext('2d');
|
|
25
|
+
}
|
|
26
|
+
// A Chart instance. `instanceof Chart` only works when the consumer and the
|
|
27
|
+
// chart under test resolve to the same chart.js copy, the canvas check does
|
|
28
|
+
// not care.
|
|
29
|
+
return actual?.ctx instanceof CanvasRenderingContext2D ? actual.ctx : null;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Logs the actual, expected and diff images to the browser console, where they
|
|
34
|
+
* can be inspected in the Vitest UI. Replaces the DOM preview Karma appended to
|
|
35
|
+
* its reporter.
|
|
36
|
+
*/
|
|
37
|
+
function logPreview(description, images) {
|
|
38
|
+
const urls = images.map(({data}) => canvasFromImageData(data).toDataURL());
|
|
39
|
+
// The preview is the point of this function: Karma appended it to its
|
|
40
|
+
// reporter, a browser test has the console instead.
|
|
41
|
+
// biome-ignore lint/suspicious/noConsole: the preview is what this function is for
|
|
42
|
+
console.log(
|
|
43
|
+
`%c ${description}\n${images.map(({label}) => label).join(' | ')}\n%c %c %c `,
|
|
44
|
+
'font: 12px monospace',
|
|
45
|
+
...urls.map((url) => `padding: 128px 128px; background: url(${url}) no-repeat center/contain`)
|
|
46
|
+
);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function toBeCloseToPixel(actual, expected) {
|
|
50
|
+
let pass = false;
|
|
51
|
+
|
|
52
|
+
if (!isNaN(actual) && !isNaN(expected)) {
|
|
53
|
+
const diff = Math.abs(actual - expected);
|
|
54
|
+
const A = Math.abs(actual);
|
|
55
|
+
const B = Math.abs(expected);
|
|
56
|
+
const percentDiff = 0.005; // 0.5% diff
|
|
57
|
+
pass = diff <= (A > B ? A : B) * percentDiff || diff < 2; // 2 pixels is fine
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
return {
|
|
61
|
+
message: () => `Expected ${actual} to be close to pixel ${expected}`,
|
|
62
|
+
pass
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function toBeCloseToPoint(actual, expected) {
|
|
67
|
+
const rnd = (v) => Math.round(v * 100) / 100;
|
|
68
|
+
return {
|
|
69
|
+
message: () => `Expected ${JSON.stringify(actual)} to be close to point ${JSON.stringify(expected)}`,
|
|
70
|
+
pass: rnd(actual.x) === rnd(expected.x) && rnd(actual.y) === rnd(expected.y)
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export function toEqualOneOf(actual, expecteds) {
|
|
75
|
+
return {
|
|
76
|
+
message: () => `Expected ${actual} to be one of ${JSON.stringify(expecteds)}`,
|
|
77
|
+
pass: expecteds.indexOf(actual) !== -1
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function toBeValidChart(actual) {
|
|
82
|
+
const Chart = getChart();
|
|
83
|
+
let message = null;
|
|
84
|
+
|
|
85
|
+
if (Chart && !(actual instanceof Chart)) {
|
|
86
|
+
message = `Expected ${actual} to be an instance of Chart`;
|
|
87
|
+
} else if (Object.prototype.toString.call(actual.canvas) !== '[object HTMLCanvasElement]') {
|
|
88
|
+
message = 'Expected canvas to be an instance of HTMLCanvasElement';
|
|
89
|
+
} else if (Object.prototype.toString.call(actual.ctx) !== '[object CanvasRenderingContext2D]') {
|
|
90
|
+
message = 'Expected context to be an instance of CanvasRenderingContext2D';
|
|
91
|
+
} else if (typeof actual.height !== 'number' || !isFinite(actual.height)) {
|
|
92
|
+
message = 'Expected height to be a strict finite number';
|
|
93
|
+
} else if (typeof actual.width !== 'number' || !isFinite(actual.width)) {
|
|
94
|
+
message = 'Expected width to be a strict finite number';
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
return {
|
|
98
|
+
message: () => message || `Expected ${actual} to be valid chart`,
|
|
99
|
+
pass: !message
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export function toBeChartOfSize(actual, expected) {
|
|
104
|
+
const valid = toBeValidChart(actual);
|
|
105
|
+
if (!valid.pass) {
|
|
106
|
+
return valid;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
let message = null;
|
|
110
|
+
const canvas = actual.ctx.canvas;
|
|
111
|
+
const style = getComputedStyle(canvas);
|
|
112
|
+
const pixelRatio = actual.options.devicePixelRatio || window.devicePixelRatio;
|
|
113
|
+
const dh = parseInt(style.height, 10) || 0;
|
|
114
|
+
const dw = parseInt(style.width, 10) || 0;
|
|
115
|
+
const rh = canvas.height;
|
|
116
|
+
const rw = canvas.width;
|
|
117
|
+
const orh = rh / pixelRatio;
|
|
118
|
+
const orw = rw / pixelRatio;
|
|
119
|
+
|
|
120
|
+
// sanity checks
|
|
121
|
+
if (actual.height !== orh) {
|
|
122
|
+
message = `Expected chart height ${actual.height} to be equal to original render height ${orh}`;
|
|
123
|
+
} else if (actual.width !== orw) {
|
|
124
|
+
message = `Expected chart width ${actual.width} to be equal to original render width ${orw}`;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// validity checks
|
|
128
|
+
if (dh !== expected.dh) {
|
|
129
|
+
message = `Expected display height ${dh} to be equal to ${expected.dh}`;
|
|
130
|
+
} else if (dw !== expected.dw) {
|
|
131
|
+
message = `Expected display width ${dw} to be equal to ${expected.dw}`;
|
|
132
|
+
} else if (rh !== expected.rh) {
|
|
133
|
+
message = `Expected render height ${rh} to be equal to ${expected.rh}`;
|
|
134
|
+
} else if (rw !== expected.rw) {
|
|
135
|
+
message = `Expected render width ${rw} to be equal to ${expected.rw}`;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
return {
|
|
139
|
+
message: () => message || `Expected ${actual} to be a chart of size ${JSON.stringify(expected)}`,
|
|
140
|
+
pass: !message
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* Compares a rendered canvas against a reference image.
|
|
146
|
+
* @param {object} actual - a Chart, a canvas or a 2d context
|
|
147
|
+
* @param {ImageData} [expected] - the reference image data
|
|
148
|
+
* @param {object} [opts] - comparison options
|
|
149
|
+
* @param {number} [opts.threshold] - per pixel color distance, see pixelmatch
|
|
150
|
+
* @param {number} [opts.tolerance] - accepted ratio of differing pixels
|
|
151
|
+
* @param {boolean} [opts.checkerboard] - blend transparency against a checkerboard instead of white
|
|
152
|
+
* @param {boolean} [opts.debug] - always fail and log the preview
|
|
153
|
+
* @param {string} [opts.description] - label for the logged preview
|
|
154
|
+
*/
|
|
155
|
+
export function toEqualImageData(actual, expected, opts = {}) {
|
|
156
|
+
const ctx = resolveContext(actual);
|
|
157
|
+
if (!ctx) {
|
|
158
|
+
return {message: () => 'Input value is not a valid image source.', pass: false};
|
|
159
|
+
}
|
|
160
|
+
if (!expected) {
|
|
161
|
+
return {message: () => 'Missing reference image.', pass: false};
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
const threshold = opts.threshold === undefined ? DEFAULT_THRESHOLD : opts.threshold;
|
|
165
|
+
const tolerance = opts.tolerance === undefined ? DEFAULT_TOLERANCE : opts.tolerance;
|
|
166
|
+
// pixelmatch 7.2.0 added a `checkerboard` option and defaulted it to true,
|
|
167
|
+
// changing how semi-transparent pixels are compared. Every reference image
|
|
168
|
+
// captured with pixelmatch 5 -- which is every image this package has ever
|
|
169
|
+
// compared -- was blended against plain white. Checkerboard blending is a
|
|
170
|
+
// different measurement rather than a stricter one: each goes blind where the
|
|
171
|
+
// ink color meets the background it is blended against. Default to white, and
|
|
172
|
+
// let a fixture opt into the checkerboard once its reference image has been
|
|
173
|
+
// re-validated against it.
|
|
174
|
+
const checkerboard = opts.checkerboard === true;
|
|
175
|
+
const {height, width} = expected;
|
|
176
|
+
const actualWidth = ctx.canvas.width;
|
|
177
|
+
const actualHeight = ctx.canvas.height;
|
|
178
|
+
|
|
179
|
+
const actualData = ctx.getImageData(0, 0, actualWidth, actualHeight);
|
|
180
|
+
const diffData = createImageData(width, height);
|
|
181
|
+
const count =
|
|
182
|
+
actualWidth === width && actualHeight === height
|
|
183
|
+
? pixelmatch(actualData.data, expected.data, diffData.data, width, height, {checkerboard, threshold})
|
|
184
|
+
: Math.abs(actualWidth * actualHeight - width * height);
|
|
185
|
+
const ratio = count / (width * height);
|
|
186
|
+
const pass = ratio <= tolerance && !opts.debug;
|
|
187
|
+
|
|
188
|
+
if (!pass) {
|
|
189
|
+
logPreview(opts.description || 'fixture', [
|
|
190
|
+
{data: actualData, label: 'actual'},
|
|
191
|
+
{data: expected, label: 'expected'},
|
|
192
|
+
{data: diffData, label: 'diff'}
|
|
193
|
+
]);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
return {
|
|
197
|
+
message: () =>
|
|
198
|
+
'Expected the rendered canvas to match the reference image.\n' +
|
|
199
|
+
` Size: ${actualWidth}x${actualHeight}, expected ${width}x${height}\n` +
|
|
200
|
+
` Difference: ${count}px / ${toPercent(ratio)}%\n` +
|
|
201
|
+
` Threshold: ${toPercent(threshold)}%, tolerance: ${toPercent(tolerance)}%`,
|
|
202
|
+
pass
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
export function toEqualOptions(actual, expected) {
|
|
207
|
+
const result = compareOptions(actual, expected);
|
|
208
|
+
return {
|
|
209
|
+
message: () => result.message || 'Expected options to differ',
|
|
210
|
+
pass: result.pass
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
export const matchers = {
|
|
215
|
+
toBeChartOfSize,
|
|
216
|
+
toBeCloseToPixel,
|
|
217
|
+
toBeCloseToPoint,
|
|
218
|
+
toBeValidChart,
|
|
219
|
+
toEqualImageData,
|
|
220
|
+
toEqualOneOf,
|
|
221
|
+
toEqualOptions
|
|
222
|
+
};
|
|
223
|
+
|
|
224
|
+
export default matchers;
|