-
Notifications
You must be signed in to change notification settings - Fork 466
Expand file tree
/
Copy pathcanvas-context.js
More file actions
56 lines (52 loc) · 1.61 KB
/
canvas-context.js
File metadata and controls
56 lines (52 loc) · 1.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// @flow
type MaybeFn = (any => any) | void;
const identity = () => {};
export default function mockCanvasContext() {
const log: Array<any> = [];
/**
* Logs canvas operations. The log will preserve the order of operations, which is
* important for canvas rendering.
*/
function spyLog(name: string, fn: MaybeFn = identity) {
// This function is extremely polymorphic and defies typing.
return (jest.fn: any)((...args) => {
log.push([name, ...args]);
if (fn) {
return fn(...args);
}
return undefined;
});
}
return new Proxy(
{
scale: spyLog('scale'),
fill: spyLog('fill'),
fillRect: spyLog('fillRect'),
fillText: spyLog('fillText'),
clearRect: spyLog('clearRect'),
beginPath: spyLog('beginPath'),
closePath: spyLog('closePath'),
arc: spyLog('arc'),
measureText: spyLog('measureText', text => ({ width: text.length * 5 })),
createLinearGradient: spyLog('createLinearGradient', () => ({
addColorStop: spyLog('addColorStop'),
})),
__flushDrawLog: (): Array<any> => {
const oldLog = log.slice();
log.splice(0, log.length);
return oldLog;
},
},
{
// Record what values are set on the context.
set(target, property, value) {
target[property] = value;
log.push(['set ' + property, value]);
return true;
},
}
);
}