This repository has been archived by the owner on Nov 1, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
window.stub.ts
78 lines (63 loc) · 2.42 KB
/
window.stub.ts
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import {SinonSandbox, SinonStub} from 'sinon';
import {sinon} from 'test-drive-react';
export type WindowEvent = WindowEventMap[keyof WindowEventMap];
type WindowEventListener = (e?: Partial<WindowEvent>) => any;
function stubWindowMethod(
sandbox: SinonSandbox,
method: keyof Window,
stub: (...args: any[]) => any
) {
return sandbox.stub(window, method).callsFake(stub);
}
export class WindowStub {
public sandbox = sinon.sandbox.create();
public addEventListener = stubWindowMethod(
this.sandbox, 'addEventListener',
(type: string, listener: WindowEventListener, useCapture?: boolean) => {
const events = useCapture ? this.eventsCapture : this.events;
if (events.has(type)) {
const listeners = events.get(type);
(listeners as WindowEventListener[]).push(listener);
} else {
const listeners = [listener];
events.set(type, listeners);
}
}
);
public removeEventListener = stubWindowMethod(
this.sandbox, 'removeEventListener',
(type: string, listener?: WindowEventListener, useCapture?: boolean) => {
const events = useCapture ? this.eventsCapture : this.events;
if (events.has(type)) {
const listeners = events.get(type);
if (listener) {
const index = listeners!.indexOf(listener);
if (index >= 0) {
listeners!.splice(index, 1);
if (listeners!.length === 0) {
events.delete(type);
}
}
} else {
events.delete(type);
}
}
}
);
private events = new Map<string, WindowEventListener[]>();
private eventsCapture = new Map<string, WindowEventListener[]>();
public simulate(type: string, event?: Partial<WindowEvent>) {
const events = this.events;
if (events.has(type)) {
const listeners = events.get(type);
listeners!.forEach(listener => listener(event));
}
}
public simulateCapture(type: string, event?: Partial<WindowEvent>) {
const events = this.eventsCapture;
if (events.has(type)) {
const listeners = events.get(type);
listeners!.forEach(listener => listener(event));
}
}
}