UNPKG

3.2 kBJavaScriptView Raw
1(function (){
2 'use strict';
3
4 Object.defineProperty(window, 'mocha', {
5 get () {
6 return undefined;
7 },
8 set (m) {
9 shimMocha(m);
10 delete window.mocha;
11 window.mocha = m;
12
13 // mochaOptions is injected in lib/client.js
14
15 mochaOptions = mochaOptions || {
16 ui: 'bdd',
17 reporter: 'spec',
18 useColors: true
19 };
20
21 mocha.setup(mochaOptions);
22 },
23 configurable: true
24 });
25
26 Object.defineProperty(window, 'Mocha', {
27 get () {
28 return undefined;
29 },
30 set (m) {
31 delete window.Mocha;
32 window.Mocha = m;
33
34 m.process.stdout._write = function (chunks, encoding, cb) {
35 var output = chunks.toString ? chunks.toString() : chunks;
36
37 window._eventbus.emit('mocha', output);
38
39 m.process.nextTick(cb);
40 };
41
42 window._eventbus.emit('width');
43 },
44 configurable: true
45 });
46
47 function shimMocha (m) {
48 var origRun = m.run, origUi = m.ui;
49
50 m.ui = function () {
51 var retval = origUi.apply(mocha, arguments);
52 m.reporter = () => {};
53 return retval;
54 };
55 m.run = function () {
56 window._eventbus.emit('started', m.suite.suites.length);
57
58 m.runner = origRun.apply(mocha, arguments);
59 if (m.runner.stats && m.runner.stats.end) {
60 window._eventbus.emit('ended', m.runner.stats);
61 }
62 else {
63 m.runner.on('end', () => {
64 window._eventbus.emit('ended', m.runner.stats);
65 });
66 }
67 return m.runner;
68 };
69 }
70
71 // Mocha needs the formating feature of console.log so copy node's format function and
72 // monkey-patch it into place. This code is copied from node's, links copyright applies.
73 // https://github.com/joyent/node/blob/master/lib/util.js
74 if (!console.format) {
75 let origError = console.error,
76 origLog = console.log;
77
78 console.format = function (f) {
79 if (typeof f !== 'string') {
80 return Array.prototype.map.call(arguments, (arg) => {
81 try {
82 return JSON.stringify(arg);
83 }
84 catch (_) {
85 return '[Circular]';
86 }
87 }).join(' ');
88 }
89 var i = 1,
90 args = arguments,
91 len = args.length,
92 str = String(f).replace(/%[sdj%]/g, (x) => {
93 if (x === '%%') return '%';
94 if (i >= len) return x;
95 switch (x) {
96 case '%s': return String(args[i++]);
97 case '%d': return Number(args[i++]);
98 case '%j':
99 try {
100 return JSON.stringify(args[i++]);
101 }
102 catch (_) {
103 return '[Circular]';
104 }
105 default:
106 return x;
107 }
108 }),
109 x;
110 for (x = args[i]; i < len; x = args[++i]) {
111 if (x === null || typeof x !== 'object') {
112 str += ' ' + x;
113 }
114 else {
115 str += ' ' + JSON.stringify(x);
116 }
117 }
118 return str;
119 };
120
121 console.error = function (){
122 origError.call(console, console.format.apply(console, arguments));
123 };
124
125 console.log = function (){
126 origLog.call(console, console.format.apply(console, arguments));
127 };
128 }
129
130})();