-
Notifications
You must be signed in to change notification settings - Fork 9.5k
/
Copy pathmock-commands.js
217 lines (203 loc) · 6.89 KB
/
mock-commands.js
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
/**
* @license
* Copyright 2019 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
/**
* @fileoverview Refer to driver-test.js and source-maps-test.js for intended usage.
*/
import {fnAny} from '../test-utils.js';
/**
* @template {keyof LH.CrdpCommands} C
* @typedef {((...args: LH.CrdpCommands[C]['paramsType']) => MockResponse<C>) | LH.Util.RecursivePartial<LH.CrdpCommands[C]['returnType']> | Promise<Error>} MockResponse
*/
/**
* @template {keyof LH.CrdpEvents} E
* @typedef {LH.Util.RecursivePartial<LH.CrdpEvents[E][0]>} MockEvent
*/
/**
* Creates a jest mock function whose implementation consumes mocked protocol responses matching the
* requested command in the order they were mocked.
*
* It is decorated with two methods:
* - `mockResponse` which pushes protocol message responses for consumption
* - `findInvocation` which asserts that `sendCommand` was invoked with the given command and
* returns the protocol message argument.
*
* To mock an error response, use `send.mockResponse('Command', () => Promise.reject(error))`.
*/
function createMockSendCommandFn() {
/**
* Typescript fails to equate template type `C` here with `C` when pushing to this array.
* Instead of sprinkling a couple ts-ignores, make `command` be any, but leave `C` for just
* documentation purposes. This is an internal type, so it doesn't matter much.
* @template {keyof LH.CrdpCommands} C
* @type {Array<{command: C|any, sessionId?: string, response?: MockResponse<C>, delay?: number}>}
*/
const mockResponses = [];
const mockFnImpl = fnAny().mockImplementation(
/**
* @template {keyof LH.CrdpCommands} C
* @param {C} command
* @param {LH.CrdpCommands[C]['paramsType']} args
*/
async (command, ...args) => {
const indexOfResponse = mockResponses
.findIndex(entry => entry.command === command && entry.sessionId === undefined);
if (indexOfResponse === -1) throw new Error(`${command} unimplemented`);
const {response, delay} = mockResponses[indexOfResponse];
mockResponses.splice(indexOfResponse, 1);
const returnValue = typeof response === 'function' ? response(...args) : response;
if (delay) return new Promise(resolve => setTimeout(() => resolve(returnValue), delay));
return returnValue;
});
const mockFn = Object.assign(mockFnImpl, {
/**
* @template {keyof LH.CrdpCommands} C
* @param {C} command
* @param {MockResponse<C>=} response
* @param {number=} delay
*/
mockResponse(command, response, delay) {
mockResponses.push({command, response, delay});
return mockFn;
},
/**
* @template {keyof LH.CrdpCommands} C
* @param {C} command
* @param {string} sessionId
* @param {MockResponse<C>=} response
* @param {number=} delay
*/
mockResponseToSession(command, sessionId, response, delay) {
mockResponses.push({command, sessionId, response, delay});
return mockFn;
},
/**
* @param {keyof LH.CrdpCommands} command
*/
findInvocation(command) {
expect(mockFn).toHaveBeenCalledWith(command, expect.anything());
const call = mockFn.mock.calls.find(call => call[0] === command);
if (!call) throw new Error(`missing invocation for command: ${command}`);
return call[1];
},
/**
* @param {keyof LH.CrdpCommands} command
*/
findAllInvocations(command) {
return mockFn.mock.calls.filter(
call => call[0] === command
).map(invocation => invocation[1]);
},
});
return mockFn;
}
/**
* Creates a jest mock function whose implementation invokes `.on`/`.once` listeners after a setTimeout tick.
* Closely mirrors `createMockSendCommandFn`.
*
* It is decorated with two methods:
* - `mockEvent` which pushes protocol event payload for consumption
* - `findListener` which asserts that `on` was invoked with the given event name and
* returns the listener .
*/
function createMockOnceFn() {
/**
* @template {keyof LH.CrdpEvents} E
* @type {Array<{event: E|any, response?: MockEvent<E>}>}
*/
const mockEvents = [];
const mockFnImpl = fnAny().mockImplementation((eventName, listener) => {
const indexOfResponse = mockEvents.findIndex(entry => entry.event === eventName);
if (indexOfResponse === -1) return;
const {response} = mockEvents[indexOfResponse];
mockEvents.splice(indexOfResponse, 1);
// Wait a tick because real events never fire immediately
setTimeout(() => listener(response), 0);
});
const mockFn = Object.assign(mockFnImpl, {
/**
* @template {keyof LH.CrdpEvents} E
* @param {E} event
* @param {MockEvent<E>} response
*/
mockEvent(event, response) {
mockEvents.push({event, response});
return mockFn;
},
/**
* @param {keyof LH.CrdpEvents} event
*/
findListener(event) {
expect(mockFn).toHaveBeenCalledWith(event, expect.anything());
const call = mockFn.mock.calls.find(call => call[0] === event);
if (!call) throw new Error(`missing listener for event: ${event}`);
return call[1];
},
/**
* @param {keyof LH.CrdpEvents} event
*/
getListeners(event) {
return mockFn.mock.calls.filter(call => call[0] === event).map(call => call[1]);
},
});
return mockFn;
}
/**
* Very much like `createMockOnceFn`, but will fire all the events (not just one for every call).
* So it's good for .on w/ many events.
*/
function createMockOnFn() {
/**
* @template {keyof LH.CrdpEvents} E
* @type {Array<{event: E|any, response?: MockEvent<E>}>}
*/
const mockEvents = [];
const mockFnImpl = fnAny().mockImplementation((eventName, listener) => {
const events = mockEvents.filter(entry => entry.event === eventName);
if (!events.length) return;
for (const event of events) {
const indexOfEvent = mockEvents.indexOf(event);
mockEvents.splice(indexOfEvent, 1);
}
// Wait a tick because real events never fire immediately
setTimeout(() => {
for (const event of events) {
listener(event.response);
}
}, 0);
});
const mockFn = Object.assign(mockFnImpl, {
/**
* @template {keyof LH.CrdpEvents} E
* @param {E} event
* @param {MockEvent<E>} response
*/
mockEvent(event, response) {
mockEvents.push({event, response});
return mockFn;
},
/**
* @param {keyof LH.CrdpEvents} event
*/
findListener(event) {
expect(mockFn).toHaveBeenCalledWith(event, expect.anything());
const call = mockFn.mock.calls.find(call => call[0] === event);
if (!call) throw new Error(`missing listener for event: ${event}`);
return call[1];
},
/**
* @param {keyof LH.CrdpEvents} event
*/
getListeners(event) {
return mockFn.mock.calls.filter(call => call[0] === event).map(call => call[1]);
},
});
return mockFn;
}
export {
createMockSendCommandFn,
createMockOnceFn,
createMockOnFn,
};