-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbrowserRunner.js
269 lines (231 loc) · 8.45 KB
/
browserRunner.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
import {
runRootTestSuite
} from "./src/TestSuite.js";
import { loadJSON, validateLocalFilePath } from "./src/util/loader.js";
import TestSandbox from "./src/TestSandbox.js";
function getSearchParams() {
const searchParams = {};
const VALID_PROPERTY_REGEX = /^[a-zA-Z][\w-]*$/;
location.search.substr(1)
.split('&').map(
// Regex to split only the first occurance of '=':
param => param.split(/=(.*)/, 2)
.map(decodeURIComponent)
).forEach(([key, value]) => {
if (VALID_PROPERTY_REGEX.test(key)) {
// Treat as boolean if there's no value (hence no '=')
searchParams[key] = (value === undefined ? true : value);
}
});
return searchParams;
}
const searchParams = getSearchParams();
function generateSearchString(params) {
return Object.keys(params)
.map(name => {
const value = params[name];
if (value === undefined) {
return '';
}
if (typeof value === "boolean") {
return value ? encodeURIComponent(name) : '';
}
return `${encodeURIComponent(name)}=${encodeURIComponent(value)}`;
})
.filter(Boolean) // Remove empty strings
.join("&");
}
function generateStackTraceNode(stackTrace) {
const pre = document.createElement("pre");
// Add as text content to escape HTML
pre.textContent = stackTrace;
// Then escape URLs (if they don't have any special characters in them)
pre.innerHTML = pre.innerHTML.replace(
/https?:\/\/[^\s"'<>&]+\.jsm?/g,
'<a href="$&" target="_blank">$&</a>'
)
return pre;
}
function generateSuiteResultElement(resultNode, parentPath="") {
const ul = document.createElement('ul');
Object.keys(resultNode).forEach(testName => {
// Strip off query param (but only if it's a root test name, which are file paths)
const testLabel = (parentPath ? testName : testName.replace(/\?.*$/, ""));
const testResult = resultNode[testName];
const li = document.createElement('li');
const {success, error} = testResult;
const testPath = parentPath ? `${parentPath}:${testName}` : testName;
li.className = success ? "success" : "failure";
li.textContent = `${success ? "✓" : "failed:"} ${testLabel}`;
const directLink = "?" + generateSearchString(
Object.assign(searchParams, {
testPath: testPath
})
);
if (error) {
li.textContent = `Failed: ${li.textContent}`;
}
li.innerHTML += ` <a class="run-test" href="${directLink}">Isolate</a>`;
if (error) {
const errorTextDiv = document.createElement('div');
errorTextDiv.textContent = String(error && error.message || error);
li.appendChild(errorTextDiv);
if (error.stack) {
li.appendChild(generateStackTraceNode(error.stack));
}
}
if (testResult.subTests && Object.keys(testResult.subTests).length) {
const expandToggle = document.createElement('input');
expandToggle.type = "checkbox";
expandToggle.className = "expand";
expandToggle.checked = !testResult.success;
expandToggle.id = testPath;
const expandLabel = document.createElement('label');
expandLabel.htmlFor = testPath;
expandLabel.appendChild(li.firstChild);
li.insertBefore(expandLabel, li.firstChild);
li.insertBefore(expandToggle, li.firstChild);
li.appendChild(generateSuiteResultElement(testResult.subTests, testPath));
}
ul.appendChild(li);
});
return ul;
}
function recordResults(finished = false, results = {}, coverage) {
window['__esmunit_results__'] = {
finished,
results,
coverage,
success: !Object.keys(results).some(testName => !results[testName].success),
}
}
function displayResults(finished, testFiles, results) {
let container = document.querySelector('#test_results');
if (!container) {
container = document.createElement('div');
container.id = "test_results";
document.body.appendChild(container);
}
container.classList.toggle('results-finished', finished);
container.classList.toggle('results-unfinished', !finished);
if (!container.querySelector('header')) {
const header = document.createElement('header');
header.innerHTML = `<div><progress></div><div><button id="expand_all">Expand All</button><button id="collapse_all">Collase All</button><button id="expand_failed">Only Failures</button></div>`;
header.querySelector('#expand_all').addEventListener('click',
() => container.querySelectorAll('input.expand').forEach(input => input.checked = true)
);
header.querySelector('#collapse_all').addEventListener('click',
() => container.querySelectorAll('input.expand').forEach(input => input.checked = false)
);
header.querySelector('#expand_failed').addEventListener('click',
() => container.querySelectorAll('li').forEach(li => {
expander = li.querySelectorAll('input.expand')[0];
if (expander) {
expander.checked = li.classList.contains('failure');
}
})
);
if (searchParams.testPath) {
header.innerHTML += `<button id="run_all_tests">Run All tests</button>`;
header.querySelector('#run_all_tests').addEventListener('click', () => {
location.search = `?` + generateSearchString(
Object.assign(searchParams, {
testPath: undefined
})
);
});
}
container.appendChild(header);
container.appendChild(document.createElement('main'));
}
const progress = container.querySelector('header progress');
progress.max = testFiles.length ?? 1;
progress.value = results ? Object.keys(results).length : 0;
container.querySelector('main').innerHTML = '';
container.querySelector('main').appendChild(generateSuiteResultElement(results));
}
function makeErrorResult(error) {
return {
success: false,
error: error,
};
}
function runAllTests(testPath, testSandboxes, testAggregator) {
return runRootTestSuite(testPath, testAggregator)
.then(results => {
testSandboxes.filter(sandbox => sandbox.error)
.forEach(sandboxWithError => {
const sandboxPath = sandboxWithError.filePath;
results[sandboxPath] = makeErrorResult(sandboxWithError.error);
});
return results;
});
}
function loadConfig(configSrc) {
if (configSrc) {
return loadJSON(validateLocalFilePath(configSrc));
} else {
return Promise.resolve({});
}
}
// Expose as globals so they can be accessed from compiled projects
window['__esmunit__api__'] = {
"runRootTestSuite": runRootTestSuite,
};
window.addEventListener("load", () => {
let {
testFile,
testPath,
module,
debug = false,
config: configSrc,
} = searchParams;
let testFiles = [];
let testSandboxes = [];
let config;
if (testPath && typeof testPath === "string") {
testPath = testPath.split(":");
}
let aggregatedResults = {};
const testAggregator = (testPath, testName, results) => {
// Only show top-level results for now
if (!testPath) {
aggregatedResults[testName] = results;
displayResults(false, testFiles, aggregatedResults);
recordResults(false, aggregatedResults);
}
};
const startTime = Date.now();
const timediff = () => `${(Date.now() - startTime)/1000}s`;
return loadConfig(configSrc)
.then(_config => {
console.debug(`Loaded config at ${timediff()}`);
config = _config;
if (module === undefined && 'module' in config) {
module = config['module'] ?? true;
}
if (Array.isArray(config['testFiles'])) {
testFiles = config['testFiles'];
}
if (testFile) {
testFiles = [testFile];
}
// If a path is provided, the file being tested is the first item of the path.
// Load only that file.
const fileInPath = testPath && testPath[0];
if (fileInPath) {
testFiles = testFiles.filter(testFile => testFile === fileInPath);
}
testSandboxes = testFiles.map(testFile => new TestSandbox(testFile, module, config, debug));
testSandboxes.forEach(sandbox => sandbox.register());
console.debug(`Registered tests at ${timediff()}`);
recordResults();
return runAllTests(testPath, testSandboxes, testAggregator);
})
.then(results => {
console.debug(`Completed tests at ${timediff()}`);
const coverageReports = testSandboxes.map(sandbox => sandbox.getCoverageReport());
recordResults(true, results, coverageReports);
displayResults(true, testFiles, results);
});
});