-
Notifications
You must be signed in to change notification settings - Fork 176
/
browser.js
1834 lines (1810 loc) · 63.5 KB
/
browser.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
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @license
* Copyright (c) 2014 The Polymer Project Authors. All rights reserved.
* This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
* The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
* The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
* Code distributed by Google as part of the polymer project is also
* subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/
/**
* THIS FILE IS AUTOMATICALLY GENERATED!
* To make changes to browser.js, please edit the source files in the repo's `browser/` directory!
*/
(function () {
'use strict';
window.__wctUseNpm = false;
/**
* @license
* Copyright (c) 2014 The Polymer Project Authors. All rights reserved.
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt The complete set of authors may be found
* at http://polymer.github.io/AUTHORS.txt The complete set of contributors may
* be found at http://polymer.github.io/CONTRIBUTORS.txt Code distributed by
* Google as part of the polymer project is also subject to an additional IP
* rights grant found at http://polymer.github.io/PATENTS.txt
*/
// Make sure that we use native timers, in case they're being stubbed out.
var nativeSetInterval = window.setInterval;
var nativeSetTimeout = window.setTimeout;
var nativeRequestAnimationFrame = window.requestAnimationFrame;
/**
* Runs `stepFn`, catching any error and passing it to `callback` (Node-style).
* Otherwise, calls `callback` with no arguments on success.
*
* @param {function()} callback
* @param {function()} stepFn
*/
function safeStep(callback, stepFn) {
var err;
try {
stepFn();
}
catch (error) {
err = error;
}
callback(err);
}
/**
* Runs your test at declaration time (before Mocha has begun tests). Handy for
* when you need to test document initialization.
*
* Be aware that any errors thrown asynchronously cannot be tied to your test.
* You may want to catch them and pass them to the done event, instead. See
* `safeStep`.
*
* @param {string} name The name of the test.
* @param {function(?function())} testFn The test function. If an argument is
* accepted, the test will be treated as async, just like Mocha tests.
*/
function testImmediate(name, testFn) {
if (testFn.length > 0) {
return testImmediateAsync(name, testFn);
}
var err;
try {
testFn();
}
catch (error) {
err = error;
}
test(name, function (done) {
done(err);
});
}
/**
* An async-only variant of `testImmediate`.
*
* @param {string} name
* @param {function(?function())} testFn
*/
function testImmediateAsync(name, testFn) {
var testComplete = false;
var err;
test(name, function (done) {
var intervalId = nativeSetInterval(function () {
if (!testComplete)
return;
clearInterval(intervalId);
done(err);
}, 10);
});
try {
testFn(function (error) {
if (error)
err = error;
testComplete = true;
});
}
catch (error) {
err = error;
testComplete = true;
}
}
/**
* Triggers a flush of any pending events, observations, etc and calls you back
* after they have been processed.
*
* @param {function()} callback
*/
function flush(callback) {
// Ideally, this function would be a call to Polymer.dom.flush, but that
// doesn't support a callback yet
// (https://github.com/Polymer/polymer-dev/issues/851),
// ...and there's cross-browser flakiness to deal with.
// Make sure that we're invoking the callback with no arguments so that the
// caller can pass Mocha callbacks, etc.
var done = function done() {
callback();
};
// Because endOfMicrotask is flaky for IE, we perform microtask checkpoints
// ourselves (https://github.com/Polymer/polymer-dev/issues/114):
var isIE = navigator.appName === 'Microsoft Internet Explorer';
if (isIE && window.Platform && window.Platform.performMicrotaskCheckpoint) {
var reallyDone_1 = done;
done = function doneIE() {
Platform.performMicrotaskCheckpoint();
nativeSetTimeout(reallyDone_1, 0);
};
}
// Everyone else gets a regular flush.
var scope;
if (window.Polymer && window.Polymer.dom && window.Polymer.dom.flush) {
scope = window.Polymer.dom;
}
else if (window.Polymer && window.Polymer.flush) {
scope = window.Polymer;
}
else if (window.WebComponents && window.WebComponents.flush) {
scope = window.WebComponents;
}
if (scope) {
scope.flush();
}
// Ensure that we are creating a new _task_ to allow all active microtasks to
// finish (the code you're testing may be using endOfMicrotask, too).
nativeSetTimeout(done, 0);
}
/**
* Advances a single animation frame.
*
* Calls `flush`, `requestAnimationFrame`, `flush`, and `callback` sequentially
* @param {function()} callback
*/
function animationFrameFlush(callback) {
flush(function () {
nativeRequestAnimationFrame(function () {
flush(callback);
});
});
}
/**
* DEPRECATED: Use `flush`.
* @param {function} callback
*/
function asyncPlatformFlush(callback) {
console.warn('asyncPlatformFlush is deprecated in favor of the more terse flush()');
return window.flush(callback);
}
/**
*
*/
function waitFor(fn, next, intervalOrMutationEl, timeout, timeoutTime) {
timeoutTime = timeoutTime || Date.now() + (timeout || 1000);
intervalOrMutationEl = intervalOrMutationEl || 32;
try {
fn();
}
catch (e) {
if (Date.now() > timeoutTime) {
throw e;
}
else {
if (typeof intervalOrMutationEl !== 'number') {
intervalOrMutationEl.onMutation(intervalOrMutationEl, function () {
waitFor(fn, next, intervalOrMutationEl, timeout, timeoutTime);
});
}
else {
nativeSetTimeout(function () {
waitFor(fn, next, intervalOrMutationEl, timeout, timeoutTime);
}, intervalOrMutationEl);
}
return;
}
}
next();
}
window.safeStep = safeStep;
window.testImmediate = testImmediate;
window.testImmediateAsync = testImmediateAsync;
window.flush = flush;
window.animationFrameFlush = animationFrameFlush;
window.asyncPlatformFlush = asyncPlatformFlush;
window.waitFor = waitFor;
/**
* The global configuration state for WCT's browser client.
*/
var _config = {
environmentScripts: !!window.__wctUseNpm ?
[
'stacky/browser.js', 'async/lib/async.js', 'lodash/index.js',
'mocha/mocha.js', 'chai/chai.js', '@polymer/sinonjs/sinon.js',
'sinon-chai/lib/sinon-chai.js',
'accessibility-developer-tools/dist/js/axs_testing.js',
'@polymer/test-fixture/test-fixture.js'
] :
[
'stacky/browser.js', 'async/lib/async.js', 'lodash/lodash.js',
'mocha/mocha.js', 'chai/chai.js', 'sinonjs/sinon.js',
'sinon-chai/lib/sinon-chai.js',
'accessibility-developer-tools/dist/js/axs_testing.js'
],
environmentImports: !!window.__wctUseNpm ? [] :
['test-fixture/test-fixture.html'],
root: null,
waitForFrameworks: true,
waitFor: null,
numConcurrentSuites: 1,
trackConsoleError: true,
mochaOptions: { timeout: 10 * 1000 },
verbose: false,
};
/**
* Merges initial `options` into WCT's global configuration.
*
* @param {Object} options The options to merge. See `browser/config.js` for a
* reference.
*/
function setup(options) {
var childRunner = ChildRunner.current();
if (childRunner) {
_deepMerge(_config, childRunner.parentScope.WCT._config);
// But do not force the mocha UI
delete _config.mochaOptions.ui;
}
if (options && typeof options === 'object') {
_deepMerge(_config, options);
}
if (!_config.root) {
// Sibling dependencies.
var root = scriptPrefix('browser.js');
_config.root = basePath(root.substr(0, root.length - 1));
if (!_config.root) {
throw new Error('Unable to detect root URL for WCT sources. Please set WCT.root before including browser.js');
}
}
}
/**
* Retrieves a configuration value.
*/
function get(key) {
return _config[key];
}
// Internal
function _deepMerge(target, source) {
Object.keys(source).forEach(function (key) {
if (target[key] !== null && typeof target[key] === 'object' &&
!Array.isArray(target[key])) {
_deepMerge(target[key], source[key]);
}
else {
target[key] = source[key];
}
});
}
/**
* @param {function()} callback A function to call when the active web component
* frameworks have loaded.
*/
function whenFrameworksReady(callback) {
debug('whenFrameworksReady');
var done = function () {
debug('whenFrameworksReady done');
callback();
};
// If webcomponents script is in the document, wait for WebComponentsReady.
if (window.WebComponents && !window.WebComponents.ready) {
debug('WebComponentsReady?');
window.addEventListener('WebComponentsReady', function wcReady() {
window.removeEventListener('WebComponentsReady', wcReady);
debug('WebComponentsReady');
done();
});
}
else {
done();
}
}
/**
* @return {string} '<count> <kind> tests' or '<count> <kind> test'.
*/
function pluralizedStat(count, kind) {
if (count === 1) {
return count + ' ' + kind + ' test';
}
else {
return count + ' ' + kind + ' tests';
}
}
/**
* @param {string} path The URI of the script to load.
* @param {function} done
*/
function loadScript(path, done) {
var script = document.createElement('script');
script.src = path;
if (done) {
script.onload = done.bind(null, null);
script.onerror = done.bind(null, 'Failed to load script ' + script.src);
}
document.head.appendChild(script);
}
/**
* @param {string} path The URI of the stylesheet to load.
* @param {function} done
*/
function loadStyle(path, done) {
var link = document.createElement('link');
link.rel = 'stylesheet';
link.href = path;
if (done) {
link.onload = done.bind(null, null);
link.onerror = done.bind(null, 'Failed to load stylesheet ' + link.href);
}
document.head.appendChild(link);
}
/**
* @param {...*} var_args Logs values to the console when the `debug`
* configuration option is true.
*/
function debug() {
var var_args = [];
for (var _i = 0; _i < arguments.length; _i++) {
var_args[_i] = arguments[_i];
}
if (!get('verbose')) {
return;
}
var args = [window.location.pathname].concat(var_args);
(console.debug || console.log).apply(console, args);
}
// URL Processing
/**
* @param {string} url
* @return {{base: string, params: string}}
*/
function parseUrl(url) {
var parts = url.match(/^(.*?)(?:\?(.*))?$/);
return {
base: parts[1],
params: getParams(parts[2] || ''),
};
}
/**
* Expands a URL that may or may not be relative to `base`.
*
* @param {string} url
* @param {string} base
* @return {string}
*/
function expandUrl(url, base) {
if (!base)
return url;
if (url.match(/^(\/|https?:\/\/)/))
return url;
if (base.substr(base.length - 1) !== '/') {
base = base + '/';
}
return base + url;
}
/**
* @param {string=} opt_query A query string to parse.
* @return {!Object<string, !Array<string>>} All params on the URL's query.
*/
function getParams(query) {
query = typeof query === 'string' ? query : window.location.search;
if (query.substring(0, 1) === '?') {
query = query.substring(1);
}
// python's SimpleHTTPServer tacks a `/` on the end of query strings :(
if (query.slice(-1) === '/') {
query = query.substring(0, query.length - 1);
}
if (query === '')
return {};
var result = {};
query.split('&').forEach(function (part) {
var pair = part.split('=');
if (pair.length !== 2) {
console.warn('Invalid URL query part:', part);
return;
}
var key = decodeURIComponent(pair[0]);
var value = decodeURIComponent(pair[1]);
if (!result[key]) {
result[key] = [];
}
result[key].push(value);
});
return result;
}
/**
* Merges params from `source` into `target` (mutating `target`).
*
* @param {!Object<string, !Array<string>>} target
* @param {!Object<string, !Array<string>>} source
*/
function mergeParams(target, source) {
Object.keys(source).forEach(function (key) {
if (!(key in target)) {
target[key] = [];
}
target[key] = target[key].concat(source[key]);
});
}
/**
* @param {string} param The param to return a value for.
* @return {?string} The first value for `param`, if found.
*/
function getParam(param) {
var params = getParams();
return params[param] ? params[param][0] : null;
}
/**
* @param {!Object<string, !Array<string>>} params
* @return {string} `params` encoded as a URI query.
*/
function paramsToQuery(params) {
var pairs = [];
Object.keys(params).forEach(function (key) {
params[key].forEach(function (value) {
pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));
});
});
return (pairs.length > 0) ? ('?' + pairs.join('&')) : '';
}
function getPathName(location) {
return typeof location === 'string' ? location : location.pathname;
}
function basePath(location) {
return getPathName(location).match(/^.*\//)[0];
}
function relativeLocation(location, basePath) {
var path = getPathName(location);
if (path.indexOf(basePath) === 0) {
path = path.substring(basePath.length);
}
return path;
}
function cleanLocation(location) {
var path = getPathName(location);
if (path.slice(-11) === '/index.html') {
path = path.slice(0, path.length - 10);
}
return path;
}
function parallel(runners, maybeLimit, done) {
var limit;
if (typeof maybeLimit !== 'number') {
done = maybeLimit;
limit = 0;
}
else {
limit = maybeLimit;
}
if (!runners.length) {
return done();
}
var called = false;
var total = runners.length;
var numActive = 0;
var numDone = 0;
function runnerDone(error) {
if (called) {
return;
}
numDone = numDone + 1;
numActive = numActive - 1;
if (error || numDone >= total) {
called = true;
done(error);
}
else {
runOne();
}
}
function runOne() {
if (limit && numActive >= limit) {
return;
}
if (!runners.length) {
return;
}
numActive = numActive + 1;
runners.shift()(runnerDone);
}
runners.forEach(runOne);
}
/**
* Finds the directory that a loaded script is hosted on.
*
* @param {string} filename
* @return {string?}
*/
function scriptPrefix(filename) {
var scripts = document.querySelectorAll('script[src*="' + filename + '"]');
if (scripts.length !== 1) {
return null;
}
var script = scripts[0].src;
return script.substring(0, script.indexOf(filename));
}
var util = Object.freeze({
whenFrameworksReady: whenFrameworksReady,
pluralizedStat: pluralizedStat,
loadScript: loadScript,
loadStyle: loadStyle,
debug: debug,
parseUrl: parseUrl,
expandUrl: expandUrl,
getParams: getParams,
mergeParams: mergeParams,
getParam: getParam,
paramsToQuery: paramsToQuery,
basePath: basePath,
relativeLocation: relativeLocation,
cleanLocation: cleanLocation,
parallel: parallel,
scriptPrefix: scriptPrefix
});
/**
* A Mocha suite (or suites) run within a child iframe, but reported as if they
* are part of the current context.
*/
var ChildRunner = /** @class */ (function () {
function ChildRunner(url, parentScope) {
var urlBits = parseUrl(url);
mergeParams(urlBits.params, getParams(parentScope.location.search));
delete urlBits.params.cli_browser_id;
this.url = urlBits.base + paramsToQuery(urlBits.params);
this.parentScope = parentScope;
this.state = 'initializing';
}
/**
* @return {ChildRunner} The `ChildRunner` that was registered for this
* window.
*/
ChildRunner.current = function () {
return ChildRunner.get(window);
};
/**
* @param {!Window} target A window to find the ChildRunner of.
* @param {boolean} traversal Whether this is a traversal from a child window.
* @return {ChildRunner} The `ChildRunner` that was registered for `target`.
*/
ChildRunner.get = function (target, traversal) {
var childRunner = ChildRunner._byUrl[target.location.href];
if (childRunner) {
return childRunner;
}
if (window.parent === window) { // Top window.
if (traversal) {
console.warn('Subsuite loaded but was never registered. This most likely is due to wonky history behavior. Reloading...');
window.location.reload();
}
return null;
}
// Otherwise, traverse.
return window.parent.WCT._ChildRunner.get(target, true);
};
/**
* Loads and runs the subsuite.
*
* @param {function} done Node-style callback.
*/
ChildRunner.prototype.run = function (done) {
debug('ChildRunner#run', this.url);
this.state = 'loading';
this.onRunComplete = done;
this.iframe = document.createElement('iframe');
this.iframe.src = this.url;
this.iframe.classList.add('subsuite');
var container = document.getElementById('subsuites');
if (!container) {
container = document.createElement('div');
container.id = 'subsuites';
document.body.appendChild(container);
}
container.appendChild(this.iframe);
// let the iframe expand the URL for us.
this.url = this.iframe.src;
ChildRunner._byUrl[this.url] = this;
this.timeoutId = setTimeout(this.loaded.bind(this, new Error('Timed out loading ' + this.url)), ChildRunner.loadTimeout);
this.iframe.addEventListener('error', this.loaded.bind(this, new Error('Failed to load document ' + this.url)));
this.iframe.contentWindow.addEventListener('DOMContentLoaded', this.loaded.bind(this, null));
};
/**
* Called when the sub suite's iframe has loaded (or errored during load).
*
* @param {*} error The error that occured, if any.
*/
ChildRunner.prototype.loaded = function (error) {
debug('ChildRunner#loaded', this.url, error);
if (this.iframe.contentWindow == null && error) {
this.signalRunComplete(error);
this.done();
return;
}
// Not all targets have WCT loaded (compatiblity mode)
if (this.iframe.contentWindow.WCT) {
this.share = this.iframe.contentWindow.WCT.share;
}
if (error) {
this.signalRunComplete(error);
this.done();
}
};
/**
* Called in mocha/run.js when all dependencies have loaded, and the child is
* ready to start running tests
*
* @param {*} error The error that occured, if any.
*/
ChildRunner.prototype.ready = function (error) {
debug('ChildRunner#ready', this.url, error);
if (this.timeoutId) {
clearTimeout(this.timeoutId);
}
if (error) {
this.signalRunComplete(error);
this.done();
}
};
/**
* Called when the sub suite's tests are complete, so that it can clean up.
*/
ChildRunner.prototype.done = function () {
debug('ChildRunner#done', this.url, arguments);
// make sure to clear that timeout
this.ready();
this.signalRunComplete();
if (!this.iframe)
return;
// Be safe and avoid potential browser crashes when logic attempts to
// interact with the removed iframe.
setTimeout(function () {
this.iframe.parentNode.removeChild(this.iframe);
this.iframe = null;
this.share = null;
}.bind(this), 1);
};
ChildRunner.prototype.signalRunComplete = function (error) {
if (!this.onRunComplete)
return;
this.state = 'complete';
this.onRunComplete(error);
this.onRunComplete = null;
};
// ChildRunners get a pretty generous load timeout by default.
ChildRunner.loadTimeout = 60000;
// We can't maintain properties on iframe elements in Firefox/Safari/???, so
// we track childRunners by URL.
ChildRunner._byUrl = {};
return ChildRunner;
}());
var SOCKETIO_ENDPOINT = window.location.protocol + '//' + window.location.host;
var SOCKETIO_LIBRARY = SOCKETIO_ENDPOINT + '/socket.io/socket.io.js';
/**
* A socket for communication between the CLI and browser runners.
*
* @param {string} browserId An ID generated by the CLI runner.
* @param {!io.Socket} socket The socket.io `Socket` to communicate over.
*/
var CLISocket = /** @class */ (function () {
function CLISocket(browserId, socket) {
this.browserId = browserId;
this.socket = socket;
}
/**
* @param {!Mocha.Runner} runner The Mocha `Runner` to observe, reporting
* interesting events back to the CLI runner.
*/
CLISocket.prototype.observe = function (runner) {
var _this = this;
this.emitEvent('browser-start', {
url: window.location.toString(),
});
// We only emit a subset of events that we care about, and follow a more
// general event format that is hopefully applicable to test runners beyond
// mocha.
//
// For all possible mocha events, see:
// https://github.com/visionmedia/mocha/blob/master/lib/runner.js#L36
runner.on('test', function (test) {
_this.emitEvent('test-start', { test: getTitles(test) });
});
runner.on('test end', function (test) {
_this.emitEvent('test-end', {
state: getState(test),
test: getTitles(test),
duration: test.duration,
error: test.err,
});
});
runner.on('fail', function (test, err) {
// fail the test run if we catch errors outside of a test function
if (test.type !== 'test') {
_this.emitEvent('browser-fail', 'Error thrown outside of test function: ' + err.stack);
}
});
runner.on('childRunner start', function (childRunner) {
_this.emitEvent('sub-suite-start', childRunner.share);
});
runner.on('childRunner end', function (childRunner) {
_this.emitEvent('sub-suite-end', childRunner.share);
});
runner.on('end', function () {
_this.emitEvent('browser-end');
});
};
/**
* @param {string} event The name of the event to fire.
* @param {*} data Additional data to pass with the event.
*/
CLISocket.prototype.emitEvent = function (event, data) {
this.socket.emit('client-event', {
browserId: this.browserId,
event: event,
data: data,
});
};
/**
* Builds a `CLISocket` if we are within a CLI-run environment; short-circuits
* otherwise.
*
* @param {function(*, CLISocket)} done Node-style callback.
*/
CLISocket.init = function (done) {
var browserId = getParam('cli_browser_id');
if (!browserId)
return done();
// Only fire up the socket for root runners.
if (ChildRunner.current())
return done();
loadScript(SOCKETIO_LIBRARY, function (error) {
if (error)
return done(error);
var socket = io(SOCKETIO_ENDPOINT);
socket.on('error', function (error) {
socket.off();
done(error);
});
socket.on('connect', function () {
socket.off();
done(null, new CLISocket(browserId, socket));
});
});
};
return CLISocket;
}());
// Misc Utility
/**
* @param {!Mocha.Runnable} runnable The test or suite to extract titles from.
* @return {!Array.<string>} The titles of the runnable and its parents.
*/
function getTitles(runnable) {
var titles = [];
while (runnable && !runnable.root && runnable.title) {
titles.unshift(runnable.title);
runnable = runnable.parent;
}
return titles;
}
/**
* @param {!Mocha.Runnable} runnable
* @return {string}
*/
function getState(runnable) {
if (runnable.state === 'passed') {
return 'passing';
}
else if (runnable.state === 'failed') {
return 'failing';
}
else if (runnable.pending) {
return 'pending';
}
else {
return 'unknown';
}
}
// We capture console events when running tests; so make sure we have a
// reference to the original one.
var console$1 = window.console;
var FONT = ';font: normal 13px "Roboto", "Helvetica Neue", "Helvetica", sans-serif;';
var STYLES = {
plain: FONT,
suite: 'color: #5c6bc0' + FONT,
test: FONT,
passing: 'color: #259b24' + FONT,
pending: 'color: #e65100' + FONT,
failing: 'color: #c41411' + FONT,
stack: 'color: #c41411',
results: FONT + 'font-size: 16px',
};
// I don't think we can feature detect this one...
var userAgent = navigator.userAgent.toLowerCase();
var CAN_STYLE_LOG = userAgent.match('firefox') || userAgent.match('webkit');
var CAN_STYLE_GROUP = userAgent.match('webkit');
// Track the indent for faked `console.group`
var logIndent = '';
function log(text, style) {
text = text.split('\n')
.map(function (l) {
return logIndent + l;
})
.join('\n');
if (CAN_STYLE_LOG) {
console$1.log('%c' + text, STYLES[style] || STYLES.plain);
}
else {
console$1.log(text);
}
}
function logGroup(text, style) {
if (CAN_STYLE_GROUP) {
console$1.group('%c' + text, STYLES[style] || STYLES.plain);
}
else if (console$1.group) {
console$1.group(text);
}
else {
logIndent = logIndent + ' ';
log(text, style);
}
}
function logGroupEnd() {
if (console$1.groupEnd) {
console$1.groupEnd();
}
else {
logIndent = logIndent.substr(0, logIndent.length - 2);
}
}
function logException(error) {
log(error.stack || error.message || (error + ''), 'stack');
}
/**
* A Mocha reporter that logs results out to the web `console`.
*/
var Console = /** @class */ (function () {
/**
* @param runner The runner that is being reported on.
*/
function Console(runner) {
Mocha.reporters.Base.call(this, runner);
runner.on('suite', function (suite) {
if (suite.root) {
return;
}
logGroup(suite.title, 'suite');
}.bind(this));
runner.on('suite end', function (suite) {
if (suite.root) {
return;
}
logGroupEnd();
}.bind(this));
runner.on('test', function (test) {
logGroup(test.title, 'test');
}.bind(this));
runner.on('pending', function (test) {
logGroup(test.title, 'pending');
}.bind(this));
runner.on('fail', function (_test, error) {
logException(error);
}.bind(this));
runner.on('test end', function (_test) {
logGroupEnd();
}.bind(this));
runner.on('end', this.logSummary.bind(this));
}
/** Prints out a final summary of test results. */
Console.prototype.logSummary = function () {
logGroup('Test Results', 'results');
if (this.stats.failures > 0) {
log(pluralizedStat(this.stats.failures, 'failing'), 'failing');
}
if (this.stats.pending > 0) {
log(pluralizedStat(this.stats.pending, 'pending'), 'pending');
}
log(pluralizedStat(this.stats.passes, 'passing'));
if (!this.stats.failures) {
log('test suite passed', 'passing');
}
log('Evaluated ' + this.stats.tests + ' tests in ' +
this.stats.duration + 'ms.');
logGroupEnd();
};
return Console;
}());
/**
* @license
* Copyright (c) 2014 The Polymer Project Authors. All rights reserved.
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt The complete set of authors may be found
* at http://polymer.github.io/AUTHORS.txt The complete set of contributors may
* be found at http://polymer.github.io/CONTRIBUTORS.txt Code distributed by
* Google as part of the polymer project is also subject to an additional IP
* rights grant found at http://polymer.github.io/PATENTS.txt
*/
/**
* WCT-specific behavior on top of Mocha's default HTML reporter.
*
* @param {!Mocha.Runner} runner The runner that is being reported on.
*/
function HTML(runner) {
var output = document.createElement('div');
output.id = 'mocha';
document.body.appendChild(output);
runner.on('suite', function (_test) {
this.total = runner.total;
}.bind(this));
Mocha.reporters.HTML.call(this, runner);
}
// Woo! What a hack. This just saves us from adding a bunch of complexity around
// style loading.
var style = document.createElement('style');
style.textContent = "\n html, body {\n position: relative;\n height: 100%;\n width: 100%;\n min-width: 900px;\n }\n #mocha, #subsuites {\n height: 100%;\n position: absolute;\n top: 0;\n }\n #mocha {\n box-sizing: border-box;\n margin: 0 !important;\n padding: 60px 20px;\n right: 0;\n left: 500px;\n }\n #subsuites {\n -ms-flex-direction: column;\n -webkit-flex-direction: column;\n display: -ms-flexbox;\n display: -webkit-flex;\n display: flex;\n flex-direction: column;\n left: 0;\n width: 500px;\n }\n #subsuites .subsuite {\n border: 0;\n width: 100%;\n height: 100%;\n }\n #mocha .test.pass .duration {\n color: #555 !important;\n }\n";
document.head.appendChild(style);
var STACKY_CONFIG = {
indent: ' ',
locationStrip: [
/^https?:\/\/[^\/]+/,
/\?.*$/,
],
filter: function (line) {
return !!line.location.match(/\/web-component-tester\/[^\/]+(\?.*)?$/);
},
};
// https://github.com/visionmedia/mocha/blob/master/lib/runner.js#L36-46
var MOCHA_EVENTS = [
'start', 'end', 'suite', 'suite end', 'test', 'test end', 'hook', 'hook end',
'pass', 'fail', 'pending', 'childRunner end'
];
// Until a suite has loaded, we assume this many tests in it.
var ESTIMATED_TESTS_PER_SUITE = 3;
/**
* A Mocha-like reporter that combines the output of multiple Mocha suites.
*/
var MultiReporter = /** @class */ (function () {
/**
* @param numSuites The number of suites that will be run, in order to
* estimate the total number of tests that will be performed.
* @param reporters The set of reporters that
* should receive the unified event stream.
* @param parent The parent reporter, if present.
*/
function MultiReporter(numSuites, reporters, parent) {
var _this = this;
this.reporters = reporters.map(function (reporter) {
return new reporter(_this);
});
this.parent = parent;
this.basePath = parent && parent.basePath || basePath(window.location);
this.total = numSuites * ESTIMATED_TESTS_PER_SUITE;
// Mocha reporters assume a stream of events, so we have to be careful to
// only report on one runner at a time...
this.currentRunner = null;
// ...while we buffer events for any other active runners.
this.pendingEvents = [];
this.emit('start');
}
/**
* @param location The location this reporter represents.
* @return A reporter-like "class" for each child suite
* that should be passed to `mocha.run`.
*/