forked from ampproject/amphtml
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest-helper.js
More file actions
421 lines (385 loc) · 11.7 KB
/
test-helper.js
File metadata and controls
421 lines (385 loc) · 11.7 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
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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
/**
* Copyright 2016 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {WindowInterface} from '../src/window-interface';
import {
getService,
getServiceForDoc,
registerServiceBuilder,
registerServiceBuilderForDoc,
resetServiceForTesting,
} from '../src/service';
import {getStyle} from '../src/style';
import {poll} from './iframe';
export function stubService(sandbox, win, serviceId, method) {
// Register if not already registered.
registerServiceBuilder(win, serviceId, function () {
return {
[method]: () => {},
};
});
const service = getService(win, serviceId);
return sandbox.stub(service, method);
}
export function stubServiceForDoc(sandbox, ampdoc, serviceId, method) {
// Register if not already registered.
registerServiceBuilderForDoc(ampdoc, serviceId, function () {
return {
[method]: () => {},
};
});
const service = getServiceForDoc(ampdoc, serviceId);
return sandbox.stub(service, method);
}
export function mockServiceForDoc(sandbox, ampdoc, serviceId, methods) {
resetServiceForTesting(ampdoc.win, serviceId);
const impl = {};
methods.forEach((method) => {
impl[method] = () => {};
});
registerServiceBuilderForDoc(ampdoc, serviceId, function () {
return impl;
});
const mock = {};
methods.forEach((method) => {
mock[method] = sandbox.stub(impl, method);
});
return mock;
}
export function mockWindowInterface(sandbox) {
const methods = Object.getOwnPropertyNames(WindowInterface).filter(
(p) => typeof WindowInterface[p] === 'function'
);
const mock = {};
methods.forEach((method) => {
mock[method] = sandbox.stub(WindowInterface, method);
});
return mock;
}
/**
* Resolves a promise when a spy has been called a configurable number of times.
* @param {!Object} spy
* @param {number=} opt_callCount
* @return {!Promise}
*/
export function whenCalled(spy, opt_callCount = 1) {
return poll(
`Spy was called ${opt_callCount} times`,
() => spy.callCount === opt_callCount
);
}
/**
* Resolves a promise when the callback returns a truthy value.
* @param {function():?} callback
* @param {string} errorMessage
* @return {!Promise}
*/
export function waitFor(callback, errorMessage) {
return poll(
errorMessage,
callback,
undefined /* opt_onError */,
200 /* opt_timeout */
);
}
const noneValues = {
'animation-name': ['none', 'initial'],
'animation-duration': ['0s', 'initial'],
'animation-timing-function': ['ease', 'initial'],
'animation-delay': ['0s', 'initial'],
'animation-iteration-count': ['1', 'initial'],
'animation-direction': ['normal', 'initial'],
'animation-fill-mode': ['none', 'initial'],
'animation-play-state': ['running', 'initial', /* IE11 */ ''],
};
/**
* Browsers are inconsistent when accessing the value for 'animation: none'.
* Some return 'none', some return the full shorthand, some give the full
* shorthand in a different order.
* @param {!Element} element
* @return {boolean}
*/
export function isAnimationNone(element) {
for (const property in noneValues) {
const value = getStyle(element, property);
const expectedValues = noneValues[property];
if (!expectedValues.some((expectedValue) => value == expectedValue)) {
return false;
}
}
return true;
}
/**
* Asserts that the given element is only visible to screen readers.
* @param {!Element} node
* @param {{
* index: (number|undefined),
* }} options
*/
export function assertScreenReaderElement(element, {index = 0} = {}) {
const offset = index * 8;
expect(element).to.exist;
expect(element.classList.contains('i-amphtml-screen-reader')).to.be.true;
const win = element.ownerDocument.defaultView;
const computedStyle = win.getComputedStyle(element);
expect(computedStyle.getPropertyValue('position')).to.equal('fixed');
expect(computedStyle.getPropertyValue('top')).to.equal('0px');
expect(computedStyle.getPropertyValue('left')).to.equal(`${offset}px`);
expect(computedStyle.getPropertyValue('width')).to.equal('4px');
expect(computedStyle.getPropertyValue('height')).to.equal('4px');
expect(computedStyle.getPropertyValue('opacity')).to.equal('0');
expect(computedStyle.getPropertyValue('overflow')).to.equal('hidden');
expect(computedStyle.getPropertyValue('border')).to.contain('none');
expect(computedStyle.getPropertyValue('margin')).to.equal('0px');
expect(computedStyle.getPropertyValue('padding')).to.equal('0px');
expect(computedStyle.getPropertyValue('display')).to.equal('block');
expect(computedStyle.getPropertyValue('visibility')).to.equal('visible');
}
// Use a browserId to avoid cross-browser race conditions.
// TODO(amphtml): Remove browserId now that we no longer test on Sauce Labs.
/** @const {string} */
const browserId = (Date.now() + Math.random()).toString(32);
/** @const {string} */
const REQUEST_URL = '//localhost:9876/amp4test/request-bank/' + browserId;
/**
* A server side temporary request storage which is useful for testing
* browser sent HTTP requests.
*/
export class RequestBank {
static getBrowserId() {
return browserId;
}
/**
* Returns the URL for depositing a request.
*
* @param {number|string|undefined} requestId
* @returns {string}
*/
static getUrl(requestId) {
return `${REQUEST_URL}/deposit/${requestId}/`;
}
/**
* Returns a Promise that resolves when the request of given ID is deposited.
* The returned promise resolves to an JsonObject contains the request info:
* {
* url: string
* headers: JsonObject
* body: string
* }
* @param {number|string|undefined} requestId
* @returns {Promise<JsonObject>}
*/
static withdraw(requestId) {
const url = `${REQUEST_URL}/withdraw/${requestId}/`;
return RequestBank.fetch_(url, `withdraw(${requestId ?? ''})`).then((res) =>
res.json()
);
}
static tearDown() {
const url = `${REQUEST_URL}/teardown/`;
return RequestBank.fetch_(url, 'tearDown');
}
static fetch_(url, action, timeout = 10000) {
const xhr = fetch(url).then((response) => {
const {ok, status, statusText} = response;
if (!ok) {
throw new Error(
`RequestBank.${action}: HTTP ${status} error -- ${statusText}`
);
}
return response;
});
if (timeout <= 0) {
return xhr;
}
const timer = new Promise((_, reject) => {
setTimeout(() => {
reject(
new Error(`"RequestBank.${action}" timed out after ${timeout} ms.`)
);
}, timeout);
});
return Promise.race([xhr, timer]);
}
}
export class BrowserController {
constructor(win, opt_rootNode) {
this.win_ = win;
this.rootNode_ = opt_rootNode || this.win_.document;
}
wait(duration) {
return new Promise((resolve) => {
setTimeout(resolve, duration);
});
}
/**
* Helper to support providing already-selected elements to methods.
* @param {string|Element} selectorOrElement
* @return {Element}
*/
querySelectorOrElement(selectorOrElement) {
return typeof selectorOrElement == 'string'
? this.rootNode_.querySelector(selectorOrElement)
: selectorOrElement;
}
/**
* Helper to support providing already-selected elements to methods.
* @param {string|Element} selectorOrElement
* @return {Array<Element>}
*/
querySelectorAllOrElement(selectorOrElement) {
return typeof selectorOrElement == 'string'
? this.rootNode_.querySelectorAll(selectorOrElement)
: [selectorOrElement];
}
/**
* @param {string} hostSelector
* @param {number=} timeout
* @return {!Promise}
*/
waitForShadowRoot(hostSelectorOrElement, timeout = 10000) {
const element = this.querySelectorOrElement(hostSelectorOrElement);
if (!element) {
throw new Error(
`BrowserController query failed: ${hostSelectorOrElement}`
);
}
return poll(
`"${hostSelectorOrElement}" to host shadow doc`,
() => !!element.shadowRoot,
/* onError */ undefined,
timeout
);
}
/**
* @param {string} selector
* @param {number=} timeout
* @return {!Promise}
*/
waitForElementBuild(selectorOrElement, timeout = 5000) {
const elements = this.querySelectorAllOrElement(selectorOrElement);
if (!elements.length) {
throw new Error(`BrowserController query failed: ${selectorOrElement}`);
}
return poll(
`"${selectorOrElement}" to build`,
() => {
const someNotBuilt = [].some.call(elements, (e) =>
e.classList.contains('i-amphtml-notbuilt')
);
return !someNotBuilt;
},
/* onError */ undefined,
timeout
);
}
/**
* @param {string} selector
* @param {number=} timeout
* @return {!Promise}
*/
waitForElementLayout(selectorOrElement, timeout = 10000) {
const elements = this.querySelectorAllOrElement(selectorOrElement);
if (!elements.length) {
throw new Error(`BrowserController query failed: ${selectorOrElement}`);
}
return poll(
`"${selectorOrElement}" to layout`,
() => {
// AMP elements set `readyState` to complete when their
// layoutCallback() promise is resolved.
const someNotReady = [].some.call(
elements,
(e) => e.readyState !== 'complete'
);
return !someNotReady;
},
/* onError */ undefined,
timeout
);
}
click(selectorOrElement) {
const element = this.querySelectorOrElement(selectorOrElement);
if (element) {
element.dispatchEvent(new /*OK*/ CustomEvent('click', {bubbles: true}));
}
}
scrollTo(px) {
this.win_.scrollTo(0, px);
}
}
export function createPointerEvent(type, x, y) {
const event = new /*OK*/ CustomEvent(type, {bubbles: true});
event.clientX = x;
event.clientY = y;
event.pageX = x;
event.pageY = y;
event.touches = [
{
clientX: x,
clientY: y,
pageX: x,
pageY: y,
},
];
return event;
}
export class ImagePixelVerifier {
constructor(windowInterface) {
this.imagePixels_ = [];
const FakeImage = () => {
const pixel = {};
this.imagePixels_.push(pixel);
return pixel;
};
windowInterface.getImage.returns(FakeImage);
}
hasRequestSent() {
return this.imagePixels_.length > 0;
}
verifyRequest(url, referrerPolicy) {
const pixel = this.imagePixels_.shift();
expect(pixel.src).to.equal(url);
expect(pixel.referrerPolicy).to.equal(referrerPolicy);
}
verifyRequestMatch(regex) {
const pixel = this.imagePixels_.shift();
expect(pixel.src).to.match(regex);
}
getLastRequestUrl() {
if (!this.hasRequestSent()) {
return null;
}
return this.imagePixels_[this.imagePixels_.length - 1].src;
}
verifyAndRemoveRequestUrl(url) {
for (let i = this.imagePixels_.length - 1; i >= 0; i--) {
if (this.imagePixels_[i].src == url) {
this.imagePixels_.splice(i, 1);
return true;
}
}
return false;
}
}
export function measureMutateElementStub(measure, mutate) {
return Promise.resolve().then(measure).then(mutate);
}
export function measureElementStub(measure) {
return measureMutateElementStub(measure);
}
export function mutateElementStub(mutate) {
return measureMutateElementStub(undefined, mutate);
}