Debian Codegraph @

lib/reporters/html.js

raw symbols SCIP
1 "use strict";
2
3 /**
4 * @typedef {import('../runner.js')} Runner
5 */
6
7 /* eslint-env browser */
8 /**
9 * @module HTML
10 */
11 /**
12 * Module dependencies.
13 */
14
15 var Base = require("./base");
16 var utils = require("../utils");
17 var escapeRe = require("escape-string-regexp");
18 var constants = require("../runner").constants;
19 var EVENT_TEST_PASS = constants.EVENT_TEST_PASS;
20 var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;
21 var EVENT_SUITE_BEGIN = constants.EVENT_SUITE_BEGIN;
22 var EVENT_SUITE_END = constants.EVENT_SUITE_END;
23 var EVENT_TEST_PENDING = constants.EVENT_TEST_PENDING;
24 var escape = utils.escape;
25
26 /**
27 * Save timer references to avoid Sinon interfering (see GH-237).
28 */
29
30 var Date = global.Date;
31
32 /**
33 * Expose `HTML`.
34 */
35
36 exports = module.exports = HTML;
37
38 /**
39 * Stats template: Result, progress, passes, failures, and duration.
40 */
41
42 var statsTemplate =
43 '<ul id="mocha-stats">' +
44 '<li class="result"></li>' +
45 '<li class="progress-contain"><progress class="progress-element" max="100" value="0"></progress><svg class="progress-ring"><circle class="ring-flatlight" stroke-dasharray="100%,0%"/><circle class="ring-highlight" stroke-dasharray="0%,100%"/></svg><div class="progress-text">0%</div></li>' +
46 '<li class="passes"><a href="javascript:void(0);">passes:</a> <em>0</em></li>' +
47 '<li class="failures"><a href="javascript:void(0);">failures:</a> <em>0</em></li>' +
48 '<li class="duration">duration: <em>0</em>s</li>' +
49 "</ul>";
50
51 var playIcon = "&#x2023;";
52
53 /**
54 * Constructs a new `HTML` reporter instance.
55 *
56 * @public
57 * @class
58 * @memberof Mocha.reporters
59 * @extends Mocha.reporters.Base
60 * @param {Runner} runner - Instance triggers reporter actions.
61 * @param {Object} [options] - runner options
62 */
63 function HTML(runner, options) {
64 Base.call(this, runner, options);
65
66 var self = this;
67 var stats = this.stats;
68 var stat = fragment(statsTemplate);
69 var items = stat.getElementsByTagName("li");
70 const resultIndex = 0;
71 const progressIndex = 1;
72 const passesIndex = 2;
73 const failuresIndex = 3;
74 const durationIndex = 4;
75 /** Stat item containing the root suite pass or fail indicator (hasFailures ? '✖' : '✓') */
76 var resultIndicator = items[resultIndex];
77 /** Passes text and count */
78 const passesStat = items[passesIndex];
79 /** Stat item containing the pass count (not the word, just the number) */
80 const passesCount = passesStat.getElementsByTagName("em")[0];
81 /** Stat item linking to filter to show only passing tests */
82 const passesLink = passesStat.getElementsByTagName("a")[0];
83 /** Failures text and count */
84 const failuresStat = items[failuresIndex];
85 /** Stat item containing the failure count (not the word, just the number) */
86 const failuresCount = failuresStat.getElementsByTagName("em")[0];
87 /** Stat item linking to filter to show only failing tests */
88 const failuresLink = failuresStat.getElementsByTagName("a")[0];
89 /** Stat item linking to the duration time (not the word or unit, just the number) */
90 var duration = items[durationIndex].getElementsByTagName("em")[0];
91 var report = fragment('<ul id="mocha-report"></ul>');
92 var stack = [report];
93 var progressText = items[progressIndex].getElementsByTagName("div")[0];
94 var progressBar = items[progressIndex].getElementsByTagName("progress")[0];
95 var progressRing = [
96 items[progressIndex].getElementsByClassName("ring-flatlight")[0],
97 items[progressIndex].getElementsByClassName("ring-highlight")[0],
98 ];
99 var root = document.getElementById("mocha");
100
101 if (!root) {
102 return error("#mocha div missing, add it to your document");
103 }
104
105 // pass toggle
106 on(passesLink, "click", function (evt) {
107 evt.preventDefault();
108 unhide();
109 var name = /pass/.test(report.className) ? "" : " pass";
110 report.className = report.className.replace(/fail|pass/g, "") + name;
111 if (report.className.trim()) {
112 hideSuitesWithout("test pass");
113 }
114 });
115
116 // failure toggle
117 on(failuresLink, "click", function (evt) {
118 evt.preventDefault();
119 unhide();
120 var name = /fail/.test(report.className) ? "" : " fail";
121 report.className = report.className.replace(/fail|pass/g, "") + name;
122 if (report.className.trim()) {
123 hideSuitesWithout("test fail");
124 }
125 });
126
127 root.appendChild(stat);
128 root.appendChild(report);
129
130 runner.on(EVENT_SUITE_BEGIN, function (suite) {
131 if (suite.root) {
132 return;
133 }
134
135 // suite
136 var url = self.suiteURL(suite);
137 var el = fragment(
138 '<li class="suite"><h1><a href="%s">%s</a></h1></li>',
139 url,
140 escape(suite.title),
141 );
142
143 // container
144 stack[0].appendChild(el);
145 stack.unshift(document.createElement("ul"));
146 el.appendChild(stack[0]);
147 });
148
149 runner.on(EVENT_SUITE_END, function (suite) {
150 if (suite.root) {
151 if (stats.failures === 0) {
152 text(resultIndicator, "✓");
153 stat.className += " pass";
154 }
155 updateStats();
156 return;
157 }
158 stack.shift();
159 });
160
161 runner.on(EVENT_TEST_PASS, function (test) {
162 var url = self.testURL(test);
163 var markup =
164 '<li class="test pass %e"><h2>%e<span class="duration">%ems</span> ' +
165 '<a href="%s" class="replay">' +
166 playIcon +
167 "</a></h2></li>";
168 var el = fragment(markup, test.speed, test.title, test.duration, url);
169 self.addCodeToggle(el, test.body);
170 appendToStack(el);
171 updateStats();
172 });
173
174 runner.on(EVENT_TEST_FAIL, function (test) {
175 // Update stat items
176 text(resultIndicator, "✖");
177 stat.className += " fail";
178
179 var el = fragment(
180 '<li class="test fail"><h2>%e <a href="%e" class="replay">' +
181 playIcon +
182 "</a></h2></li>",
183 test.title,
184 self.testURL(test),
185 );
186 var stackString; // Note: Includes leading newline
187 var message = test.err.toString();
188
189 // <=IE7 stringifies to [Object Error]. Since it can be overloaded, we
190 // check for the result of the stringifying.
191 if (message === "[object Error]") {
192 message = test.err.message;
193 }
194
195 if (test.err.stack) {
196 var indexOfMessage = test.err.stack.indexOf(test.err.message);
197 if (indexOfMessage === -1) {
198 stackString = test.err.stack;
199 } else {
200 stackString = test.err.stack.slice(
201 test.err.message.length + indexOfMessage,
202 );
203 }
204 } else if (test.err.sourceURL && test.err.line !== undefined) {
205 // Safari doesn't give you a stack. Let's at least provide a source line.
206 stackString = "\n(" + test.err.sourceURL + ":" + test.err.line + ")";
207 }
208
209 stackString = stackString || "";
210
211 if (test.err.htmlMessage && stackString) {
212 el.appendChild(
213 fragment(
214 '<div class="html-error">%s\n<pre class="error">%e</pre></div>',
215 test.err.htmlMessage,
216 stackString,
217 ),
218 );
219 } else if (test.err.htmlMessage) {
220 el.appendChild(
221 fragment('<div class="html-error">%s</div>', test.err.htmlMessage),
222 );
223 } else {
224 el.appendChild(
225 fragment('<pre class="error">%e%e</pre>', message, stackString),
226 );
227 }
228
229 self.addCodeToggle(el, test.body);
230 appendToStack(el);
231 updateStats();
232 });
233
234 runner.on(EVENT_TEST_PENDING, function (test) {
235 var el = fragment(
236 '<li class="test pass pending"><h2>%e</h2></li>',
237 test.title,
238 );
239 appendToStack(el);
240 updateStats();
241 });
242
243 function appendToStack(el) {
244 // Don't call .appendChild if #mocha-report was already .shift()'ed off the stack.
245 if (stack[0]) {
246 stack[0].appendChild(el);
247 }
248 }
249
250 function updateStats() {
251 var percent = ((stats.tests / runner.total) * 100) | 0;
252 progressBar.value = percent;
253 if (progressText) {
254 // setting a toFixed that is too low, makes small changes to progress not shown
255 // setting it too high, makes the progress text longer then it needs to
256 // to address this, calculate the toFixed based on the magnitude of total
257 var decimalPlaces = Math.ceil(Math.log10(runner.total / 100));
258 text(
259 progressText,
260 percent.toFixed(Math.min(Math.max(decimalPlaces, 0), 100)) + "%",
261 );
262 }
263 if (progressRing) {
264 var radius = parseFloat(
265 getComputedStyle(progressRing[0]).getPropertyValue("r"),
266 );
267 var wholeArc = Math.PI * 2 * radius;
268 var highlightArc = percent * (wholeArc / 100);
269 // The progress ring is in 2 parts, the flatlight color and highlight color.
270 // Rendering both on top of the other, seems to make a 3rd color on the edges.
271 // To create 1 whole ring with 2 colors, both parts are inverse of the other.
272 progressRing[0].style["stroke-dasharray"] =
273 `0,${highlightArc}px,${wholeArc}px`;
274 progressRing[1].style["stroke-dasharray"] =
275 `${highlightArc}px,${wholeArc}px`;
276 }
277
278 // update stats
279 var ms = new Date() - stats.start;
280 text(passesCount, stats.passes);
281 text(failuresCount, stats.failures);
282 text(duration, (ms / 1000).toFixed(2));
283 }
284 }
285
286 /**
287 * Makes a URL, preserving querystring ("search") parameters.
288 *
289 * @param {string} s
290 * @return {string} A new URL.
291 */
292 function makeUrl(s) {
293 var search = window.location.search;
294
295 // Remove previous {grep, fgrep, invert} query parameters if present
296 if (search) {
297 search = search
298 .replace(/[?&](?:f?grep|invert)=[^&\s]*/g, "")
299 .replace(/^&/, "?");
300 }
301
302 return (
303 window.location.pathname +
304 (search ? search + "&" : "?") +
305 "grep=" +
306 encodeURIComponent(s)
307 );
308 }
309
310 /**
311 * Provide suite URL.
312 *
313 * @param {Object} [suite]
314 */
315 HTML.prototype.suiteURL = function (suite) {
316 return makeUrl("^" + escapeRe(suite.fullTitle()) + " ");
317 };
318
319 /**
320 * Provide test URL.
321 *
322 * @param {Object} [test]
323 */
324 HTML.prototype.testURL = function (test) {
325 return makeUrl("^" + escapeRe(test.fullTitle()) + "$");
326 };
327
328 /**
329 * Adds code toggle functionality for the provided test's list element.
330 *
331 * @param {HTMLLIElement} el
332 * @param {string} contents
333 */
334 HTML.prototype.addCodeToggle = function (el, contents) {
335 var h2 = el.getElementsByTagName("h2")[0];
336
337 on(h2, "click", function () {
338 pre.style.display = pre.style.display === "none" ? "block" : "none";
339 });
340
341 var pre = fragment("<pre><code>%e</code></pre>", utils.clean(contents));
342 el.appendChild(pre);
343 pre.style.display = "none";
344 };
345
346 /**
347 * Display error `msg`.
348 *
349 * @param {string} msg
350 */
351 function error(msg) {
352 document.body.appendChild(fragment('<div id="mocha-error">%s</div>', msg));
353 }
354
355 /**
356 * Return a DOM fragment from `html`.
357 *
358 * @param {string} html
359 */
360 function fragment(html) {
361 var args = arguments;
362 var div = document.createElement("div");
363 var i = 1;
364
365 div.innerHTML = html.replace(/%([se])/g, function (_, type) {
366 switch (type) {
367 case "s":
368 return String(args[i++]);
369 case "e":
370 return escape(args[i++]);
371 // no default
372 }
373 });
374
375 return div.firstChild;
376 }
377
378 /**
379 * Check for suites that do not have elements
380 * with `classname`, and hide them.
381 *
382 * @param {text} classname
383 */
384 function hideSuitesWithout(classname) {
385 var suites = document.getElementsByClassName("suite");
386 for (var i = 0; i < suites.length; i++) {
387 var els = suites[i].getElementsByClassName(classname);
388 if (!els.length) {
389 suites[i].className += " hidden";
390 }
391 }
392 }
393
394 /**
395 * Unhide .hidden suites.
396 */
397 function unhide() {
398 var els = document.getElementsByClassName("suite hidden");
399 while (els.length > 0) {
400 els[0].className = els[0].className.replace("suite hidden", "suite");
401 }
402 }
403
404 /**
405 * Set an element's text contents.
406 *
407 * @param {HTMLElement} el
408 * @param {string} contents
409 */
410 function text(el, contents) {
411 if (el.textContent) {
412 el.textContent = contents;
413 } else {
414 el.innerText = contents;
415 }
416 }
417
418 /**
419 * Listen on `event` with callback `fn`.
420 */
421 function on(el, event, fn) {
422 if (el.addEventListener) {
423 el.addEventListener(event, fn, false);
424 } else {
425 el.attachEvent("on" + event, fn);
426 }
427 }
428
429 HTML.browserOnly = true;