-
Notifications
You must be signed in to change notification settings - Fork 9.3k
/
report-ui-features-test.js
575 lines (479 loc) · 21.3 KB
/
report-ui-features-test.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
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
/**
* @license Copyright 2017 The Lighthouse 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.
*/
'use strict';
/* eslint-env jest */
const assert = require('assert').strict;
const fs = require('fs');
const jsdom = require('jsdom');
const Util = require('../../../../report/html/renderer/util.js');
const I18n = require('../../../../report/html/renderer/i18n.js');
const DOM = require('../../../../report/html/renderer/dom.js');
const DetailsRenderer = require('../../../../report/html/renderer/details-renderer.js');
const ReportUIFeatures = require('../../../../report/html/renderer/report-ui-features.js');
const CategoryRenderer = require('../../../../report/html/renderer/category-renderer.js');
const ElementScreenshotRenderer =
require('../../../../report/html/renderer/element-screenshot-renderer.js');
const RectHelpers = require('../../../../../lighthouse-core/lib/rect-helpers.js');
const CriticalRequestChainRenderer = require(
'../../../../report/html/renderer/crc-details-renderer.js');
const ReportRenderer = require('../../../../report/html/renderer/report-renderer.js');
const sampleResultsOrig = require('../../../results/sample_v2.json');
const TEMPLATE_FILE = fs.readFileSync(__dirname +
'/../../../../report/html/templates.html', 'utf8');
const TEMPLATE_FILE_REPORT = fs.readFileSync(__dirname +
'/../../../../report/html/report-template.html', 'utf8');
describe('ReportUIFeatures', () => {
let sampleResults;
let dom;
/**
* @param {LH.JSON} lhr
* @return {HTMLElement}
*/
function render(lhr) {
const detailsRenderer = new DetailsRenderer(dom);
const categoryRenderer = new CategoryRenderer(dom, detailsRenderer);
const renderer = new ReportRenderer(dom, categoryRenderer);
const reportUIFeatures = new ReportUIFeatures(dom);
const container = dom.find('main', dom._document);
renderer.renderReport(lhr, container);
reportUIFeatures.initFeatures(lhr);
return container;
}
beforeAll(() => {
global.Util = Util;
global.I18n = I18n;
global.ReportUIFeatures = ReportUIFeatures;
global.CriticalRequestChainRenderer = CriticalRequestChainRenderer;
global.DetailsRenderer = DetailsRenderer;
global.CategoryRenderer = CategoryRenderer;
global.ElementScreenshotRenderer = ElementScreenshotRenderer;
global.RectHelpers = RectHelpers;
// lazy loaded because they depend on CategoryRenderer to be available globally
global.PerformanceCategoryRenderer =
require('../../../../report/html/renderer/performance-category-renderer.js');
global.PwaCategoryRenderer =
require('../../../../report/html/renderer/pwa-category-renderer.js');
// Stub out matchMedia for Node.
global.matchMedia = function() {
return {
addListener: function() {},
};
};
const reportWithTemplates = TEMPLATE_FILE_REPORT
.replace('%%LIGHTHOUSE_TEMPLATES%%', TEMPLATE_FILE);
const document = new jsdom.JSDOM(reportWithTemplates);
global.self = document.window;
global.self.matchMedia = function() {
return {
addListener: function() {},
};
};
global.HTMLElement = document.window.HTMLElement;
global.HTMLInputElement = document.window.HTMLInputElement;
global.window = document.window;
global.window.getComputedStyle = function() {
return {
marginTop: '10px',
height: '10px',
};
};
dom = new DOM(document.window.document);
sampleResults = Util.prepareReportResult(sampleResultsOrig);
render(sampleResults);
});
afterAll(() => {
global.self = undefined;
global.Util = undefined;
global.I18n = undefined;
global.ReportUIFeatures = undefined;
global.matchMedia = undefined;
global.CriticalRequestChainRenderer = undefined;
global.DetailsRenderer = undefined;
global.CategoryRenderer = undefined;
global.ElementScreenshotRenderer = undefined;
global.RectHelpers = undefined;
global.PerformanceCategoryRenderer = undefined;
global.PwaCategoryRenderer = undefined;
global.window = undefined;
global.HTMLElement = undefined;
global.HTMLInputElement = undefined;
});
describe('initFeatures', () => {
it('should init a report', () => {
const container = render(sampleResults);
assert.equal(dom.findAll('.lh-category', container).length, 5);
});
it('should init a report with a single category', () => {
const lhr = JSON.parse(JSON.stringify(sampleResults));
lhr.categories = {
performance: lhr.categories.performance,
};
const container = render(lhr);
assert.equal(dom.findAll('.lh-category', container).length, 1);
});
describe('third-party filtering', () => {
let container;
beforeAll(() => {
const lhr = JSON.parse(JSON.stringify(sampleResults));
lhr.requestedUrl = lhr.finalUrl = 'http://www.example.com';
const webpAuditItemTemplate = sampleResults.audits['uses-webp-images'].details.items[0];
const renderBlockingAuditItemTemplate =
sampleResults.audits['render-blocking-resources'].details.items[0];
const textCompressionAuditItemTemplate =
sampleResults.audits['uses-text-compression'].details.items[0];
// Interleave first/third party URLs to test restoring order.
lhr.audits['uses-webp-images'].details.items = [
{
...webpAuditItemTemplate,
url: 'http://www.cdn.com/img1.jpg', // Third party, will be filtered.
},
{
...webpAuditItemTemplate,
url: 'http://www.example.com/img2.jpg', // First party, not filtered.
},
{
...webpAuditItemTemplate,
url: 'http://www.notexample.com/img3.jpg', // Third party, will be filtered.
},
];
// Test sub-item rows.
lhr.audits['unused-javascript'].details.items = [
{
...webpAuditItemTemplate,
url: 'http://www.cdn.com/script1.js', // Third party, will be filtered.
subItems: {
type: 'subitems',
items: [
{source: '1', sourceBytes: 1, sourceWastedBytes: 1},
{source: '2', sourceBytes: 2, sourceWastedBytes: 2},
],
},
},
{
...webpAuditItemTemplate,
url: 'http://www.example.com/script2.js', // First party, not filtered.
subItems: {
type: 'subitems',
items: [
{source: '3', sourceBytes: 3, sourceWastedBytes: 3},
{source: '4', sourceBytes: 4, sourceWastedBytes: 4},
],
},
},
{
...webpAuditItemTemplate,
url: 'http://www.notexample.com/script3.js', // Third party, will be filtered.
subItems: {
type: 'subitems',
items: [
{source: '5', sourceBytes: 5, sourceWastedBytes: 5},
{source: '6', sourceBytes: 6, sourceWastedBytes: 6},
],
},
},
];
// Sample json currently doesn't have any results for `unused-javascript`, so
// headings is empty. Can delete this block of code if that changes.
expect(lhr.audits['unused-javascript'].details.headings).toHaveLength(0);
lhr.audits['unused-javascript'].details.headings = [
/* t-disable max-len */
{key: 'url', valueType: 'url', subItemsHeading: {key: 'source', valueType: 'code'}},
{key: 'totalBytes', valueType: 'bytes', subItemsHeading: {key: 'sourceBytes'}},
{key: 'wastedBytes', valueType: 'bytes', subItemsHeading: {key: 'sourceWastedBytes'}},
/* eslint-enable max-len */
];
// Only third party URLs to test that checkbox is hidden
lhr.audits['render-blocking-resources'].details.items = [
{
...renderBlockingAuditItemTemplate,
url: 'http://www.cdn.com/script1.js', // Third party.
},
{
...renderBlockingAuditItemTemplate,
url: 'http://www.google.com/script2.js', // Third party.
},
{
...renderBlockingAuditItemTemplate,
url: 'http://www.notexample.com/script3.js', // Third party.
},
];
// Only first party URLs to test that checkbox is hidden
lhr.audits['uses-text-compression'].details.items = [
{
...textCompressionAuditItemTemplate,
url: 'http://www.example.com/font1.ttf', // First party.
},
{
...textCompressionAuditItemTemplate,
url: 'http://www.example.com/font2.ttf', // First party.
},
{
...textCompressionAuditItemTemplate,
url: 'http://www.example.com/font3.ttf', // First party.
},
];
// render a report onto the UIFeature dom
container = render(lhr);
});
it('filters out third party resources in on click', () => {
const filterCheckbox = dom.find('#uses-webp-images .lh-3p-filter-input', container);
function getUrlsInTable() {
return dom
.findAll(
'#uses-webp-images tr:not(.lh-row--hidden) .lh-text__url a:first-child', container)
.map(el => el.textContent);
}
expect(getUrlsInTable()).toEqual(['/img1.jpg', '/img2.jpg', '/img3.jpg']);
filterCheckbox.click();
expect(getUrlsInTable()).toEqual(['/img2.jpg']);
filterCheckbox.click();
expect(getUrlsInTable()).toEqual(['/img1.jpg', '/img2.jpg', '/img3.jpg']);
});
it('filters out sub-item rows of third party resources on click', () => {
dom.find('#unused-javascript', container);
const filterCheckbox = dom.find('#unused-javascript .lh-3p-filter-input', container);
function getRowIdentifiers() {
return dom
.findAll(
'#unused-javascript tbody tr:not(.lh-row--hidden)', container)
.map(el => el.textContent);
}
const initialExpected = [
'/script1.js(www.cdn.com)24.0 KiB8.8 KiB',
'10.0 KiB0.0 KiB',
'20.0 KiB0.0 KiB',
'/script2.js(www.example.com)24.0 KiB8.8 KiB',
'30.0 KiB0.0 KiB',
'40.0 KiB0.0 KiB',
'/script3.js(www.notexample.com)24.0 KiB8.8 KiB',
'50.0 KiB0.0 KiB',
'60.0 KiB0.0 KiB',
];
expect(getRowIdentifiers()).toEqual(initialExpected);
filterCheckbox.click();
expect(getRowIdentifiers()).toEqual([
'/script2.js(www.example.com)24.0 KiB8.8 KiB',
'30.0 KiB0.0 KiB',
'40.0 KiB0.0 KiB',
]);
filterCheckbox.click();
expect(getRowIdentifiers()).toEqual(initialExpected);
});
it('adds no filter for audits in thirdPartyFilterAuditExclusions', () => {
const checkboxClassName = 'lh-3p-filter-input';
const yesCheckbox = dom.find(`#uses-webp-images .${checkboxClassName}`, container);
expect(yesCheckbox).toBeTruthy();
expect(() => dom.find(`#uses-rel-preconnect .${checkboxClassName}`, container))
.toThrowError('query #uses-rel-preconnect .lh-3p-filter-input not found');
});
it('filter is disabled and checked for when just third party resources', () => {
const filterCheckbox =
dom.find('#render-blocking-resources .lh-3p-filter-input', container);
expect(filterCheckbox.disabled).toEqual(true);
expect(filterCheckbox.checked).toEqual(true);
});
it('filter is disabled and not checked for just first party resources', () => {
const filterCheckbox = dom.find('#uses-text-compression .lh-3p-filter-input', container);
expect(filterCheckbox.disabled).toEqual(true);
expect(filterCheckbox.checked).toEqual(false);
});
});
});
describe('fireworks', () => {
it('should render an non-all 100 report without fireworks', () => {
const lhr = JSON.parse(JSON.stringify(sampleResults));
lhr.categories.performance.score = 0.5;
const container = render(lhr);
assert.ok(container.querySelector('.score100') === null, 'has no fireworks treatment');
});
it('should render an all 100 report with fireworks', () => {
const lhr = JSON.parse(JSON.stringify(sampleResults));
Object.values(lhr.categories).forEach(element => {
element.score = 1;
});
const container = render(lhr);
assert.ok(container.querySelector('.score100'), 'has fireworks treatment');
});
it('should show fireworks for all 100s except PWA', () => {
const lhr = JSON.parse(JSON.stringify(sampleResults));
Object.values(lhr.categories).forEach(element => {
element.score = 1;
});
lhr.categories.pwa.score = 0;
const container = render(lhr);
assert.ok(container.querySelector('.score100'), 'has fireworks treatment');
});
it('should not render fireworks if all core categories are not present', () => {
const lhr = JSON.parse(JSON.stringify(sampleResults));
delete lhr.categories.performance;
delete lhr.categoryGroups.performace;
Object.values(lhr.categories).forEach(element => {
element.score = 1;
});
const container = render(lhr);
assert.ok(container.querySelector('.score100') === null, 'has no fireworks treatment');
});
});
describe('metric descriptions', () => {
it('with no errors, hide by default', () => {
const lhr = JSON.parse(JSON.stringify(sampleResults));
const container = render(lhr);
assert.ok(!container.querySelector('.lh-metrics-toggle__input').checked);
});
it('with error, show by default', () => {
const lhr = JSON.parse(JSON.stringify(sampleResults));
lhr.audits['first-contentful-paint'].errorMessage = 'Error.';
const container = render(lhr);
assert.ok(container.querySelector('.lh-metrics-toggle__input').checked);
});
});
describe('tools button', () => {
let window;
let dropDown;
beforeEach(() => {
window = dom.document().defaultView;
const features = new ReportUIFeatures(dom);
features.initFeatures(sampleResults);
dropDown = features._dropDown;
});
it('click should toggle active class', () => {
dropDown._toggleEl.click();
assert.ok(dropDown._toggleEl.classList.contains('active'));
dropDown._toggleEl.click();
assert.ok(!dropDown._toggleEl.classList.contains('active'));
});
it('Escape key removes active class', () => {
dropDown._toggleEl.click();
assert.ok(dropDown._toggleEl.classList.contains('active'));
const escape = new window.KeyboardEvent('keydown', {keyCode: /* ESC */ 27});
dom.document().dispatchEvent(escape);
assert.ok(!dropDown._toggleEl.classList.contains('active'));
});
['ArrowUp', 'ArrowDown', 'Enter', ' '].forEach((code) => {
it(`'${code}' adds active class`, () => {
const event = new window.KeyboardEvent('keydown', {code});
dropDown._toggleEl.dispatchEvent(event);
assert.ok(dropDown._toggleEl.classList.contains('active'));
});
});
it('ArrowUp on the first menu element should focus the last element', () => {
dropDown._toggleEl.click();
const arrowUp = new window.KeyboardEvent('keydown', {bubbles: true, code: 'ArrowUp'});
dropDown._menuEl.firstElementChild.dispatchEvent(arrowUp);
assert.strictEqual(dom.document().activeElement, dropDown._menuEl.lastElementChild);
});
it('ArrowDown on the first menu element should focus the second element', () => {
dropDown._toggleEl.click();
const {nextElementSibling} = dropDown._menuEl.firstElementChild;
const arrowDown = new window.KeyboardEvent('keydown', {bubbles: true, code: 'ArrowDown'});
dropDown._menuEl.firstElementChild.dispatchEvent(arrowDown);
assert.strictEqual(dom.document().activeElement, nextElementSibling);
});
it('Home on the last menu element should focus the first element', () => {
dropDown._toggleEl.click();
const {firstElementChild} = dropDown._menuEl;
const home = new window.KeyboardEvent('keydown', {bubbles: true, code: 'Home'});
dropDown._menuEl.lastElementChild.dispatchEvent(home);
assert.strictEqual(dom.document().activeElement, firstElementChild);
});
it('End on the first menu element should focus the last element', () => {
dropDown._toggleEl.click();
const {lastElementChild} = dropDown._menuEl;
const end = new window.KeyboardEvent('keydown', {bubbles: true, code: 'End'});
dropDown._menuEl.firstElementChild.dispatchEvent(end);
assert.strictEqual(dom.document().activeElement, lastElementChild);
});
describe('_getNextSelectableNode', () => {
let createDiv;
beforeAll(() => {
createDiv = () => dom.document().createElement('div');
});
it('should return undefined when nodes is empty', () => {
const nodes = [];
const nextNode = dropDown._getNextSelectableNode(nodes);
assert.strictEqual(nextNode, undefined);
});
it('should return the only node when start is defined', () => {
const node = createDiv();
const nextNode = dropDown._getNextSelectableNode([node], node);
assert.strictEqual(nextNode, node);
});
it('should return first node when start is undefined', () => {
const nodes = [createDiv(), createDiv()];
const nextNode = dropDown._getNextSelectableNode(nodes);
assert.strictEqual(nextNode, nodes[0]);
});
it('should return second node when start is first node', () => {
const nodes = [createDiv(), createDiv()];
const nextNode = dropDown._getNextSelectableNode(nodes, nodes[0]);
assert.strictEqual(nextNode, nodes[1]);
});
it('should return first node when start is second node', () => {
const nodes = [createDiv(), createDiv()];
const nextNode = dropDown._getNextSelectableNode(nodes, nodes[1]);
assert.strictEqual(nextNode, nodes[0]);
});
it('should skip the undefined node', () => {
const nodes = [createDiv(), undefined, createDiv()];
const nextNode = dropDown._getNextSelectableNode(nodes, nodes[0]);
assert.strictEqual(nextNode, nodes[2]);
});
it('should skip the disabled node', () => {
const disabledNode = createDiv();
disabledNode.setAttribute('disabled', true);
const nodes = [createDiv(), disabledNode, createDiv()];
const nextNode = dropDown._getNextSelectableNode(nodes, nodes[0]);
assert.strictEqual(nextNode, nodes[2]);
});
});
describe('onMenuFocusOut', () => {
beforeEach(() => {
dropDown._toggleEl.click();
assert.ok(dropDown._toggleEl.classList.contains('active'));
});
it('should toggle active class when focus relatedTarget is null', () => {
const event = new window.FocusEvent('focusout', {relatedTarget: null});
dropDown.onMenuFocusOut(event);
assert.ok(!dropDown._toggleEl.classList.contains('active'));
});
it('should toggle active class when focus relatedTarget is document.body', () => {
const relatedTarget = dom.document().body;
const event = new window.FocusEvent('focusout', {relatedTarget});
dropDown.onMenuFocusOut(event);
assert.ok(!dropDown._toggleEl.classList.contains('active'));
});
it('should toggle active class when focus relatedTarget is _toggleEl', () => {
const relatedTarget = dropDown._toggleEl;
const event = new window.FocusEvent('focusout', {relatedTarget});
dropDown.onMenuFocusOut(event);
assert.ok(!dropDown._toggleEl.classList.contains('active'));
});
it('should not toggle active class when focus relatedTarget is a menu item', () => {
const relatedTarget = dropDown._getNextMenuItem();
const event = new window.FocusEvent('focusout', {relatedTarget});
dropDown.onMenuFocusOut(event);
assert.ok(dropDown._toggleEl.classList.contains('active'));
});
});
});
describe('treemap button', () => {
it('should only show button if treemap data is available', () => {
expect(sampleResults.audits['script-treemap-data']).toBeUndefined();
expect(render(sampleResults).querySelector('.lh-button.report-icon--treemap')).toBeNull();
sampleResults.audits['script-treemap-data'] = {details: {}};
expect(render(sampleResults).querySelector('.lh-button.report-icon--treemap')).toBeTruthy();
});
});
describe('data-i18n', () => {
it('should have only valid data-i18n values in template', () => {
const container = render(sampleResults);
for (const node of dom.findAll('[data-i18n]', container)) {
const val = node.getAttribute('data-i18n');
assert.ok(val in Util.UIStrings, `Invalid data-i18n value of: "${val}" found.`);
}
});
});
});