Repository navigation
Expand file tree
/
Copy pathtreemap-test-pptr.js
More file actions
289 lines (246 loc) · 10.1 KB
/
Copy pathtreemap-test-pptr.js
File metadata and controls
289 lines (246 loc) · 10.1 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
/**
* @license
* Copyright 2020 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import fs from 'fs';
import puppeteer from 'puppeteer';
import {getChromePath} from 'chrome-launcher';
import {Server} from '../../cli/test/fixtures/static-server.js';
import {LH_ROOT} from '../../shared/root.js';
const debugOptions = JSON.parse(
fs.readFileSync(LH_ROOT + '/treemap/app/debug.json', 'utf-8')
);
const portNumber = 20202;
const treemapUrl = `http://localhost:${portNumber}/dist/gh-pages/treemap/index.html`;
function getTextEncodingCode() {
const code = fs.readFileSync(LH_ROOT + '/report/renderer/text-encoding.js', 'utf-8');
return code.replace('export ', '');
}
describe('Lighthouse Treemap', () => {
console.log('\n✨ Be sure to have recently run this: yarn build-treemap');
/** @type {import('puppeteer').Browser} */
let browser;
/** @type {import('puppeteer').Page} */
let page;
/** @type {Array<string|Promise<string>>} */
let pageErrors = [];
let server;
before(async function() {
server = new Server(portNumber);
await server.listen(portNumber, 'localhost');
});
after(async function() {
await Promise.all([
server.close(),
browser && browser.close(),
]);
});
beforeEach(async () => {
if (!browser) {
browser = await puppeteer.launch({
headless: process.env.DEBUG ? false : 'new',
executablePath: getChromePath(),
});
}
page = await browser.newPage();
page.on('pageerror', e => pageErrors.push(`${e.message} ${e.stack}`));
page.on('console', (e) => {
if (e.type() === 'error' || e.type() === 'warning') {
const describe = (jsHandle) => {
return jsHandle.evaluate((obj) => {
return JSON.stringify(obj, null, 2);
});
};
const promise = Promise.all(e.args().map(describe)).then(args => {
return `${e.text()} ${args.join(' ')} ${JSON.stringify(e.location(), null, 2)}`;
});
pageErrors.push(promise);
}
});
});
async function claimErrors() {
await page.bringToFront();
await page.evaluate(() => new Promise(window.requestAnimationFrame));
const theErrors = pageErrors;
pageErrors = [];
return await Promise.all(theErrors);
}
async function ensureNoErrors() {
const errors = (await claimErrors()).filter(error => {
// Filters out a cookie deprecation error that only occurs on ToT
// This error comes from gtag.js
// https://support.google.com/tagmanager/thread/288419928/error-failed-to-execute-getvalue-on-cookiedeprecationlabel?hl=en
return !error.match(
/Failed to execute 'getValue' on 'CookieDeprecationLabel': Illegal invocation/);
});
expect(errors).toHaveLength(0);
}
afterEach(/** @this {Mocha.Context} */ async function() {
try {
if (this.currentTest?.state === 'passed') {
await ensureNoErrors();
} else {
pageErrors = [];
}
} finally {
await page.close();
}
});
describe('Recieves options', () => {
it('from debug data', async () => {
await page.goto(`${treemapUrl}?debug`, {
waitUntil: 'networkidle0',
timeout: 30000,
});
const options = await page.evaluate(() => window.__treemapOptions);
expect(options.lhr.finalDisplayedUrl).toBe(debugOptions.lhr.finalDisplayedUrl);
});
/**
* @param {{options: any, usesGzip: boolean}}
*/
async function loadFromEncodedUrl({options, useGzip}) {
const json = JSON.stringify(options);
const encoded = await page.evaluate(`
${getTextEncodingCode()}
TextEncoding.toBase64(${JSON.stringify(json)}, {gzip: ${useGzip}});
`);
await page.goto(`${treemapUrl}?gzip=${useGzip ? '1' : '0'}#${encoded}`);
await page.waitForFunction(() => {
if (window.__treemapOptions) return true;
const el = document.querySelector('#lh-log');
if (el && el.textContent.startsWith('Error')) return true;
});
}
it('from encoded fragment (no gzip)', async () => {
const options = JSON.parse(JSON.stringify(debugOptions));
options.lhr.finalDisplayedUrl += '😃😃😃';
await loadFromEncodedUrl({options, usesGzip: false});
const optionsInPage = await page.evaluate(() => window.__treemapOptions);
expect(optionsInPage.lhr.finalDisplayedUrl).toBe(options.lhr.finalDisplayedUrl);
});
it('from encoded fragment (gzip)', async () => {
const options = JSON.parse(JSON.stringify(debugOptions));
options.lhr.finalDisplayedUrl += '😃😃😃';
await loadFromEncodedUrl({options, usesGzip: true});
const optionsInPage = await page.evaluate(() => window.__treemapOptions);
expect(optionsInPage.lhr.finalDisplayedUrl).toBe(options.lhr.finalDisplayedUrl);
});
describe('handles errors', () => {
const errorTestCases = [
{
options: {lhr: 'lol'},
error: 'Error: provided json is not a Lighthouse result',
},
{
options: {lhr: {noaudits: {}}},
error: 'Error: provided json is not a Lighthouse result',
},
{
options: {lhr: {audits: {}}},
error: 'Error: provided Lighthouse result is missing audit: `script-treemap-data`',
},
];
for (let i = 0; i < errorTestCases.length; i++) {
it(`case #${i + 1}`, async () => {
const testCase = errorTestCases[i];
await loadFromEncodedUrl({options: testCase.options, usesGzip: false});
const optionsInPage = await page.evaluate(() => window.__treemapOptions);
expect(optionsInPage).toBeUndefined();
const error = await page.evaluate(() => document.querySelector('#lh-log').textContent);
expect(error).toBe(testCase.error);
const errors = await claimErrors();
expect(errors).toHaveLength(1);
expect(errors[0]).toContain(testCase.error);
});
}
});
});
describe('renders correctly', () => {
it('correctly shades coverage of gtm node', async () => {
await page.goto(`${treemapUrl}?debug`, {
waitUntil: 'networkidle0',
timeout: 30000,
});
await page.select('.view-mode-selector', '1'); // unused bytes
await page.waitForSelector('.lh-treemap--view-mode--unused-bytes');
// Identify the JS data.
const gtmNode = await page.evaluate(() => {
const d1Nodes = window.__treemapOptions.lhr.audits['script-treemap-data'].details.nodes;
const gtmNode = d1Nodes.find(n => n.name.includes('gtm.js'));
return gtmNode;
});
expect(gtmNode.unusedBytes).toBeGreaterThan(20_000);
expect(gtmNode.resourceBytes).toBeGreaterThan(20_000);
// Identify the DOM node.
const gtmElemHandle = await page.evaluateHandle(() => {
const captionEls = Array.from(document.querySelectorAll('.webtreemap-caption'));
return captionEls.find(el => el.textContent.includes('gtm.js')).parentElement;
});
expect(await gtmElemHandle.isIntersectingViewport()).toBeTruthy();
// Determine visual red shading percentage.
const percentRed = await gtmElemHandle.evaluate(node => {
const redWidthPx = parseInt(window.getComputedStyle(node, ':before').width);
const completeWidthPx = node.getBoundingClientRect().width;
return redWidthPx / completeWidthPx;
});
// Reminder! UNUSED == RED
const percentDataUnused = gtmNode.unusedBytes / gtmNode.resourceBytes;
expect(percentDataUnused).toBeGreaterThan(0);
// Assert 0.2520 ~= 0.2602 w/ 1 decimal place of precision.
// CSS pixels won't let us go to 2 decimal places.
expect(percentRed).toBeApproximately(percentDataUnused, 1);
});
it('formats captions on initial render and after zooming', async () => {
await page.goto(`${treemapUrl}?debug`, {
waitUntil: 'networkidle0',
timeout: 30000,
});
const getUnformattedCaptions = () => page.evaluate(() => {
return Array.from(document.querySelectorAll('.webtreemap-caption'))
.filter(el => !el.querySelector('.lh-text-bold') || el.textContent.includes(' · '))
.map(el => el.textContent);
});
expect(await getUnformattedCaptions()).toEqual([]);
// Click on a bundle caption to zoom in and create new child DOM nodes.
const bundleCaption = await page.evaluateHandle(() => {
const captionEls = Array.from(document.querySelectorAll('.webtreemap-caption'));
return captionEls.find(el => el.textContent.includes('coursehero.com/ssi/6.'));
});
await bundleCaption.click();
expect(await getUnformattedCaptions()).toEqual([]);
});
it('shows back button when zoomed in and navigates back to top level on click', async () => {
await page.goto(`${treemapUrl}?debug`, {
waitUntil: 'networkidle0',
timeout: 30000,
});
const isBackVisible = () => page.evaluate(() => {
const el = document.querySelector('.lh-button--back');
return el ? window.getComputedStyle(el).display !== 'none' : false;
});
const isTitleVisible = () => page.evaluate(() => {
const el = document.querySelector('.lh-header--title');
return el ? window.getComputedStyle(el).display !== 'none' : false;
});
expect(await isBackVisible()).toBe(false);
expect(await isTitleVisible()).toBe(true);
const bundleCaption = await page.evaluateHandle(() => {
const captionEls = Array.from(document.querySelectorAll('.webtreemap-caption'));
return captionEls.find(el => el.textContent.includes('coursehero.com/ssi/6.'));
});
const getStyleWidth = () => bundleCaption.evaluate(el => {
return parseInt(el.parentElement.style.width);
});
const initialWidth = await getStyleWidth();
await bundleCaption.click();
expect(await isBackVisible()).toBe(true);
expect(await isTitleVisible()).toBe(false);
expect(await getStyleWidth()).toBeGreaterThan(initialWidth);
await page.click('.lh-button--back');
expect(await isBackVisible()).toBe(false);
expect(await isTitleVisible()).toBe(true);
expect(await getStyleWidth()).toBe(initialWidth);
});
});
});