-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
mocha.ts
561 lines (427 loc) · 14.7 KB
/
mocha.ts
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
/* eslint-disable prefer-rest-params */
import _ from 'lodash'
import $errUtils, { CypressError } from './error_utils'
import $utils from './utils'
import $stackUtils from './stack_utils'
// in the browser mocha is coming back
// as window
import * as mocha from 'mocha'
const { getTestFromRunnable } = $utils
const Mocha = (mocha as any).Mocha != null ? (mocha as any).Mocha : mocha
const { Test, Runner, Runnable, Hook, Suite } = Mocha
const runnerRun = Runner.prototype.run
const runnerFail = Runner.prototype.fail
const runnerRunTests = Runner.prototype.runTests
const runnableRun = Runnable.prototype.run
const runnableClearTimeout = Runnable.prototype.clearTimeout
const runnableResetTimeout = Runnable.prototype.resetTimeout
const testRetries = Test.prototype.retries
const testClone = Test.prototype.clone
const suiteAddTest = Suite.prototype.addTest
const suiteAddSuite = Suite.prototype.addSuite
const suiteRetries = Suite.prototype.retries
const hookRetries = Hook.prototype.retries
const suiteBeforeAll = Suite.prototype.beforeAll
const suiteBeforeEach = Suite.prototype.beforeEach
const suiteAfterAll = Suite.prototype.afterAll
const suiteAfterEach = Suite.prototype.afterEach
// don't let mocha pollute the global namespace
delete (window as any).mocha
delete (window as any).Mocha
type MochaArgs = [string, Function | undefined]
function createRunnable (ctx, fnType: 'Test' | 'Suite', mochaArgs: MochaArgs, runnableFn: Function, testCallback: Function | string = '', _testConfig?: Record<string, any>) {
const runnable = runnableFn.apply(ctx, mochaArgs)
// attached testConfigOverrides will execute before `runner:test:before:run` event
if (_testConfig) {
runnable._testConfig = _testConfig
}
if (fnType === 'Test') {
// persist the original callback so we can send it to the cloud
// to prevent it from being registered as a modified test
runnable.body = testCallback.toString()
}
return runnable
}
function overloadMochaFnForConfig (fnName, specWindow) {
const _fn = specWindow[fnName]
const fnType = fnName === 'it' || fnName === 'specify' ? 'Test' : 'Suite'
function overrideMochaFn (fn) {
specWindow[fnName] = fn()
specWindow[fnName]['only'] = fn('only')
specWindow[fnName]['skip'] = fn('skip')
// override xit, xdescribe, etc
if (specWindow[`x${fnName}`]) specWindow[`x${fnName}`] = specWindow[fnName]['skip']
}
const replacementFn = function (subFn) {
return function (...args) {
/**
* @type {Cypress.Cypress}
*/
const Cypress = specWindow.Cypress
const origFn = subFn ? _fn[subFn] : _fn
// fallback to empty string for stubbed runnables written like:
// - describe('concept')
// - it('does something')
let testCallback = args[1]
if (args.length > 2 && _.isObject(args[1])) {
const _testConfig = _.extend({}, args[1]) as any
const mochaArgs: MochaArgs = [args[0], args[2]]
const originalTitle = mochaArgs[0]
// fallback to empty string for stubbed runnables written like:
// - describe('concept')
// - it('does something')
testCallback = mochaArgs[1]
const configMatchesBrowser = _testConfig.browser == null || Cypress.isBrowser(_testConfig.browser, `${fnType} config value \`{ browser }\``)
if (!configMatchesBrowser) {
mochaArgs[0] = `${originalTitle} (skipped due to browser)`
// skip test at run-time when test is marked with .only but should also be skipped the test due to the browser
if (subFn === 'only') {
mochaArgs[1] = function () {
this.skip()
}
return createRunnable(this, fnType, mochaArgs, origFn, testCallback, _testConfig)
}
// skip test with .skip func to ignore the test case and not run it
return createRunnable(this, fnType, mochaArgs, _fn['skip'], testCallback, _testConfig)
}
return createRunnable(this, fnType, mochaArgs, origFn, testCallback, _testConfig)
}
return createRunnable(this, fnType, args as MochaArgs, origFn, testCallback)
}
}
overrideMochaFn(replacementFn)
}
const ui = (specWindow, _mocha) => {
// Override mocha.ui so that the pre-require event is emitted
// with the iframe's `window` reference, rather than the parent's.
_mocha.ui = function (name) {
this._ui = Mocha.interfaces[name]
if (!this._ui) {
$errUtils.throwErrByPath('mocha.invalid_interface', { args: { name } })
}
this._ui = this._ui(this.suite)
// this causes the mocha globals in the spec window to be defined
// such as describe, it, before, beforeEach, etc
this.suite.emit('pre-require', specWindow, null, this)
// allow testConfigOverrides/suite-config-overrides
// by accepting 3 arguments to it/describe/context
overloadMochaFnForConfig('it', specWindow)
overloadMochaFnForConfig('specify', specWindow)
overloadMochaFnForConfig('describe', specWindow)
overloadMochaFnForConfig('context', specWindow)
return this
}
return _mocha.ui('bdd')
}
const setMochaProps = (specWindow, _mocha) => {
// Mocha is usually defined in the spec when used normally
// in the browser or node, so we add it as a global
// for our users too
const M = (specWindow.Mocha = Mocha)
const m = (specWindow.mocha = _mocha)
// also attach the Mocha class
// to the mocha instance for clarity
m.Mocha = M
// this needs to be part of the configuration of cypress.config.{js,ts,mjs,cjs}
// we can't just forcibly use bdd
return ui(specWindow, _mocha)
}
const createMocha = (specWindow) => {
const _mocha = new Mocha({
reporter: () => {},
timeout: false,
})
// set mocha props on the specWindow
setMochaProps(specWindow, _mocha)
// return the newly created mocha instance
return _mocha
}
const getRunner = function (_mocha) {
Runner.prototype.run = function () {
// reset our runner#run function
// so the next time we call it
// its normal again!
restoreRunnerRun()
// return the runner instance
return this
}
return _mocha.run()
}
const restoreRunnableClearTimeout = () => {
Runnable.prototype.clearTimeout = runnableClearTimeout
}
const restoreRunnableResetTimeout = () => {
Runnable.prototype.resetTimeout = runnableResetTimeout
}
const restoreRunnerRun = () => {
Runner.prototype.run = runnerRun
}
const restoreRunnerFail = () => {
Runner.prototype.fail = runnerFail
}
const restoreRunnableRun = () => {
Runnable.prototype.run = runnableRun
}
const restoreSuiteRetries = () => {
Suite.prototype.retries = suiteRetries
}
const restoreTestClone = () => {
Test.prototype.clone = testClone
}
const restoreRunnerRunTests = () => {
Runner.prototype.runTests = runnerRunTests
}
const restoreSuiteAddTest = () => {
Suite.prototype.addTest = suiteAddTest
}
const restoreSuiteAddSuite = () => {
Suite.prototype.addSuite = suiteAddSuite
}
const restoreHookRetries = () => {
Hook.prototype.retries = hookRetries
}
const restoreSuiteHooks = () => {
Suite.prototype.beforeAll = suiteBeforeAll
Suite.prototype.beforeEach = suiteBeforeEach
Suite.prototype.afterAll = suiteAfterAll
Suite.prototype.afterEach = suiteAfterEach
}
const patchSuiteRetries = () => {
Suite.prototype.retries = function (...args) {
if (args[0] !== undefined && args[0] > -1) {
const err = $errUtils.cypressErrByPath('mocha.manually_set_retries_suite', {
args: {
title: this.title,
numRetries: args[0] ?? 2,
},
})
throw err
}
return suiteRetries.apply(this, args)
}
}
const patchHookRetries = () => {
Hook.prototype.retries = function (...args) {
if (args[0] !== undefined && args[0] > -1) {
const err = $errUtils.cypressErrByPath('mocha.manually_set_retries_suite', {
args: {
title: this.parent.title,
numRetries: args[0] ?? 2,
},
})
// so this error doesn't cause a retry
getTestFromRunnable(this).retries(-1)
throw err
}
return hookRetries.apply(this, args)
}
}
// matching the current Runner.prototype.fail except
// changing the logic for determining whether this is a valid err
const patchRunnerFail = () => {
Runner.prototype.fail = function (runnable, err) {
const errMessage = _.get(err, 'message')
if (errMessage && errMessage.indexOf('Resolution method is overspecified') > -1) {
err.message = $errUtils.errByPath('mocha.overspecified', { error: err.stack }).message
}
// if this isnt a correct error object then just bail
// and call the original function
if (Object.prototype.toString.call(err) !== '[object Error]') {
return runnerFail.call(this, runnable, err)
}
// else replicate the normal mocha functionality
++this.failures
runnable.state = 'failed'
this.emit('fail', runnable, err)
}
}
const patchRunnableRun = (Cypress) => {
Runnable.prototype.run = function (...args) {
const runnable = this
Cypress.action('mocha:runnable:run', runnableRun, runnable, args)
}
}
function patchTestClone () {
Test.prototype.clone = function () {
if (this._retriesBeforeEachFailedTestFn) {
this.fn = this._retriesBeforeEachFailedTestFn
}
const ret = testClone.apply(this, arguments)
// carry over testConfigOverrides
ret._testConfig = this._testConfig
// carry over test.id
ret.id = this.id
return ret
}
}
function patchRunnerRunTests () {
Runner.prototype.runTests = function () {
const suite = arguments[0]
const _slice = suite.tests.slice
// HACK: we need to dynamically enqueue tests to suite.tests during a test run
// however Mocha calls `.slice` on this property and thus we no longer have a reference
// to the internal test queue. So we replace the .slice method
// in a way that we keep a reference to the returned array. we name it suite.testsQueue
suite.tests.slice = function () {
this.slice = _slice
const ret = _slice.apply(this, arguments)
suite.testsQueue = ret
return ret
}
const ret = runnerRunTests.apply(this, arguments)
return ret
}
}
const patchRunnableClearTimeout = () => {
Runnable.prototype.clearTimeout = function (...args) {
// call the original
runnableClearTimeout.apply(this, args)
this.timer = null
}
}
const patchSuiteAddTest = (specWindow, config) => {
Suite.prototype.addTest = function (...args) {
const test = args[0]
if (!test.invocationDetails) {
test.invocationDetails = $stackUtils.getInvocationDetails(specWindow, config)
}
const ret = suiteAddTest.apply(this, args)
test.retries = function (...args) {
if (args[0] !== undefined && args[0] > -1) {
const err = $errUtils.cypressErrByPath('mocha.manually_set_retries_test', {
args: {
title: test.title,
numRetries: args[0] ?? 2,
},
})
// so this error doesn't cause a retry
test._retries = -1
throw err
}
return testRetries.apply(this, args)
}
return ret
}
}
const patchSuiteAddSuite = (specWindow, config) => {
Suite.prototype.addSuite = function (...args) {
const suite = args[0]
if (!suite.invocationDetails) {
suite.invocationDetails = $stackUtils.getInvocationDetails(specWindow, config)
}
return suiteAddSuite.apply(this, args)
}
}
const patchRunnableResetTimeout = () => {
Runnable.prototype.resetTimeout = function () {
const runnable = this
// @ts-ignore Cypress.runner is not defined
const currentRunner = Cypress.runner
const ms = this.timeout() || 1e9
this.clearTimeout()
const getErrPath = function () {
// we've yield an explicit done callback
if (runnable.async) {
return 'mocha.async_timed_out'
}
return 'miscellaneous.test_stopped'
}
this.timer = setTimeout(() => {
// @ts-ignore Cypress.runner is not defined
if (runnable.state === 'passed' || Cypress.runner !== currentRunner) {
// this timeout can be reached at the same time that a
// user does an asynchronous `done`, so double-check
// that the test has not already passed before timing out
return
}
const err = $errUtils.errByPath(getErrPath(), { ms })
runnable.callback(err)
runnable.timedOut = true
}, ms)
}
}
const patchSuiteHooks = (specWindow, config) => {
_.each(['beforeAll', 'beforeEach', 'afterAll', 'afterEach'], (fnName) => {
const _fn = Suite.prototype[fnName]
Suite.prototype[fnName] = function (title, fn) {
const _createHook = this._createHook
this._createHook = function (title, fn) {
const hook = _createHook.call(this, title, fn)
let invocationStack = hook.invocationDetails?.stack
if (!hook.invocationDetails) {
const invocationDetails = $stackUtils.getInvocationDetails(specWindow, config)!
hook.invocationDetails = invocationDetails
invocationStack = invocationDetails.stack
}
if (this._condensedHooks) {
const err = $errUtils.errByPath('mocha.hook_registered_late', { hookTitle: fnName }) as CypressError
err.setUserInvocationStack(invocationStack)
throw err
}
return hook
}
const ret = _fn.call(this, title, fn)
this._createHook = _createHook
return ret
}
})
}
const restore = () => {
restoreRunnerRun()
restoreRunnerFail()
restoreRunnableRun()
restoreRunnableClearTimeout()
restoreRunnableResetTimeout()
restoreSuiteRetries()
restoreHookRetries()
restoreRunnerRunTests()
restoreTestClone()
restoreSuiteAddTest()
restoreSuiteAddSuite()
restoreSuiteHooks()
}
const override = (specWindow, Cypress, config) => {
patchRunnerFail()
patchRunnableRun(Cypress)
patchRunnableClearTimeout()
patchRunnableResetTimeout()
patchSuiteRetries()
patchHookRetries()
patchRunnerRunTests()
patchTestClone()
patchSuiteAddTest(specWindow, config)
patchSuiteAddSuite(specWindow, config)
patchSuiteHooks(specWindow, config)
}
const create = (specWindow, Cypress, config) => {
restore()
override(specWindow, Cypress, config)
// generate the mocha + Mocha globals
// on the specWindow, and get the new
// _mocha instance
const _mocha = createMocha(specWindow)
_mocha.slow(config('slowTestThreshold'))
const _runner = getRunner(_mocha)
_mocha.suite.file = Cypress.spec.relative
return {
_mocha,
createRootTest (title, fn) {
const r = new Test(title, fn)
_runner.suite.addTest(r)
return r
},
createTest (title, fn) {
return new Test(title, fn)
},
getRunner () {
return _runner
},
getRootSuite () {
return _mocha.suite
},
}
}
export default {
create,
restore,
}