/
helpers.js
493 lines (395 loc) · 12.5 KB
/
helpers.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
/* eslint prefer-rest-params: "off", no-console: "off", arrow-body-style: "off"*/
const { _ } = Cypress
const debug = require('debug')('spec')
const snapshotCommand = require('../plugins/snapshot/snapshotCommand')
/**
* @type {sinon.SinonMatch}
*/
const match = Cypress.sinon.match
const { stringifyShort } = snapshotCommand
const eventCleanseMap = {
snapshots: stringifyShort,
parent: stringifyShort,
tests: stringifyShort,
commands: stringifyShort,
err: stringifyShort,
invocationDetails: stringifyShort,
body: '[body]',
wallClockStartedAt: match.date,
lifecycle: match.number,
fnDuration: match.number,
duration: match.number,
afterFnDuration: match.number,
wallClockDuration: match.number,
stack: match.string,
message: '[error message]',
sourceMappedStack: match.string,
parsedStack: match.array,
}
const mochaEventCleanseMap = {
...eventCleanseMap,
start: match.date,
end: match.date,
}
const spyOn = (obj, prop, fn) => {
const _fn = obj[prop]
obj[prop] = function () {
fn.apply(this, arguments)
const ret = _fn.apply(this, arguments)
return ret
}
}
function createCypress () {
/**
* @type {sinon.SinonStub}
*/
let allStubs
/**
* @type {sinon.SinonStub}
*/
let mochaStubs
/**
* @type {sinon.SinonStub}
*/
let setRunnablesStub
const enableStubSnapshots = false
// const enableStubSnapshots = true
let autCypress
const getAutCypress = () => autCypress
const snapshotMochaEvents = () => {
expect(mochaStubs.args).to.matchSnapshot(mochaEventCleanseMap, name.mocha)
}
snapshotCommand.registerInCypress()
const backupCy = window.cy
const backupCypress = window.Cypress
beforeEach(() => {
window.cy = backupCy
window.Cypress = backupCypress
})
let onInitializedListeners = []
const onInitialized = function (fn) {
onInitializedListeners.push(fn)
}
/**
* Spawns an isolated Cypress runner as the AUT, with provided spec/fixture and optional state/config
* @param {string | ()=>void | {[key:string]: any}} mochaTestsOrFile
* @param {{state?: any, config?: any}} opts
*/
const runIsolatedCypress = (mochaTestsOrFile, opts = {}) => {
_.defaultsDeep(opts, {
state: {},
config: { video: false },
onBeforeRun () {},
})
return cy.visit('/fixtures/isolated-runner.html#/tests/cypress/fixtures/empty_spec.js')
.then({ timeout: 60000 }, (win) => {
win.runnerWs.destroy()
allStubs = cy.stub().snapshot(enableStubSnapshots)
mochaStubs = cy.stub().snapshot(enableStubSnapshots)
setRunnablesStub = cy.stub().snapshot(enableStubSnapshots)
return new Promise((resolve) => {
const runIsolatedCypress = () => {
autCypress.run.restore()
const emit = autCypress.emit
const emitMap = autCypress.emitMap
const emitThen = autCypress.emitThen
cy.stub(autCypress, 'automation').snapshot(enableStubSnapshots)
.callThrough()
.withArgs('clear:cookies')
.resolves({
foo: 'bar',
})
.withArgs('take:screenshot')
.resolves({
path: '/path/to/screenshot',
size: 12,
dimensions: { width: 20, height: 20 },
multipart: false,
pixelRatio: 1,
takenAt: new Date().toISOString(),
name: 'name',
blackout: ['.foo'],
duration: 100,
})
cy.stub(autCypress, 'emit').snapshot(enableStubSnapshots).log(false)
.callsFake(function () {
const noLog = _.includes([
'navigation:changed',
'stability:changed',
'window:load',
'url:changed',
'log:added',
'page:loading',
'window:unload',
'newListener',
], arguments[0])
const noCall = _.includes(['window:before:unload', 'mocha'], arguments[0])
const isMocha = _.includes(['mocha'], arguments[0])
if (isMocha) {
mochaStubs.apply(this, arguments)
}
noLog || allStubs.apply(this, ['emit'].concat([].slice.call(arguments)))
return noCall || emit.apply(this, arguments)
})
cy.stub(autCypress, 'emitMap').snapshot(enableStubSnapshots).log(false)
.callsFake(function () {
allStubs.apply(this, ['emitMap'].concat([].slice.call(arguments)))
return emitMap.apply(this, arguments)
})
cy.stub(autCypress, 'emitThen').snapshot(enableStubSnapshots).log(false)
.callsFake(function () {
allStubs.apply(this, ['emitThen'].concat([].slice.call(arguments)))
return emitThen.apply(this, arguments)
})
spyOn(autCypress.mocha.getRunner(), 'fail', (...args) => {
Cypress.log({
name: 'Runner Fail',
message: `${args[1]}`,
state: 'failed',
consoleProps: () => {
return {
Error: args[1],
}
},
})
})
// TODO: clean this up, sinon doesn't like wrapping things multiple times
// and this catches that error
try {
cy.spy(cy.state('window').console, 'log').as('console_log')
cy.spy(cy.state('window').console, 'error').as('console_error')
} catch (_e) {
// console was already wrapped, noop
}
onInitializedListeners.forEach((fn) => fn(autCypress))
onInitializedListeners = []
autCypress.run((failed) => {
resolve({ failed, mochaStubs, autCypress, win })
})
}
cy.spy(win.eventManager.reporterBus, 'emit').snapshot(enableStubSnapshots).as('reporterBus')
cy.spy(win.eventManager.localBus, 'emit').snapshot(enableStubSnapshots).as('localBus')
cy.stub(win.runnerWs, 'emit').snapshot(enableStubSnapshots)
.withArgs('watch:test:file')
.callsFake(() => {
autCypress = win.Cypress
cy.stub(autCypress, 'onSpecWindow').snapshot(enableStubSnapshots).callsFake((specWindow) => {
autCypress.onSpecWindow.restore()
opts.onBeforeRun({ specWindow, win, autCypress })
const testsInOwnFile = _.isString(mochaTestsOrFile)
const relativeFile = testsInOwnFile ? mochaTestsOrFile : 'cypress/fixtures/empty_spec.js'
autCypress.onSpecWindow(specWindow, [
{
absolute: relativeFile,
relative: relativeFile,
relativeUrl: `/__cypress/tests?p=${relativeFile}`,
},
])
if (testsInOwnFile) return
generateMochaTestsForWin(specWindow, mochaTestsOrFile)
specWindow.before = () => {}
specWindow.beforeEach = () => {}
specWindow.afterEach = () => {}
specWindow.after = () => {}
specWindow.describe = () => {}
})
cy.stub(autCypress, 'run').snapshot(enableStubSnapshots).callsFake(runIsolatedCypress)
})
.withArgs('is:automation:client:connected')
.yieldsAsync(true)
.withArgs('get:existing:run:state')
.callsFake((evt, cb) => {
cb(opts.state)
})
.withArgs('backend:request', 'reset:server:state')
.yieldsAsync({})
.withArgs('backend:request', 'resolve:url')
.yieldsAsync({ response: {
isOkStatusCode: true,
isHtml: true,
url: 'http://localhost:3500/fixtures/isolated-runner-inner.html',
} })
.withArgs('set:runnables')
.callsFake((...args) => {
setRunnablesStub(...args)
_.last(args)()
})
// .withArgs('preserve:run:state')
// .callsFake()
.withArgs('automation:request')
.yieldsAsync({ response: {} })
const c = _.extend({}, Cypress.config(), {
isTextTerminal: true,
spec: {
relative: 'relative/path/to/spec.js',
absolute: '/absolute/path/to/spec.js',
},
}, opts.config)
c.state = {}
cy.stub(win.runnerWs, 'on').snapshot(enableStubSnapshots)
win.Runner.start(win.document.getElementById('app'), window.btoa(JSON.stringify(c)))
})
})
}
return {
runIsolatedCypress,
snapshotMochaEvents,
onInitialized,
getAutCypress,
}
}
const createHooks = (win, hooks = []) => {
_.each(hooks, (hook) => {
if (_.isString(hook)) {
hook = { type: hook }
}
let { type, fail, fn } = hook
if (fn) {
if (hook.eval) {
const fnStr = fn.toString()
const newFn = function () {
return win.eval(`(${fnStr})`).call(this)
}
Object.defineProperty(newFn, 'length', { value: fn.length })
fn = newFn
}
return win[type](fn)
}
if (fail) {
const numFailures = fail
return win[type](() => {
if (_.isNumber(fail) && fail-- <= 0) {
debug(`hook pass after (${numFailures}) failures: ${type}`)
win.assert(true, type)
return
}
debug(`hook fail: ${type}`)
win.assert(false, type)
throw new Error(`hook failed: ${type}`)
})
}
return win[type](() => {
win.assert(true, type)
debug(`hook pass: ${type}`)
})
})
}
const createTests = (win, tests = []) => {
_.each(tests, (test) => {
if (_.isString(test)) {
test = { name: test }
}
let { name, pending, fail, fn, only } = test
let it = win.it
if (only) {
it = it['only']
}
if (fn) {
if (test.eval) {
const fnStr = fn.toString()
const newFn = function () {
return win.eval(`(${fnStr})`).call(this)
}
Object.defineProperty(newFn, 'length', { value: fn.length })
fn = newFn
}
return it(name, fn)
}
if (pending) {
return it(name)
}
if (fail) {
return it(name, () => {
if (_.isNumber(fail) && fail-- === 0) {
debug(`test pass after retry: ${name}`)
win.assert(true, name)
return
}
debug(`test fail: ${name}`)
win.assert(false, name)
throw new Error(`test fail: ${name}`)
})
}
return it(name, () => {
debug(`test pass: ${name}`)
win.assert(true, name)
})
})
}
const createSuites = (win, suites = {}) => {
_.each(suites, (obj, suiteName) => {
let fn = () => {
createHooks(win, obj.hooks)
createTests(win, obj.tests)
createSuites(win, obj.suites)
}
if (_.isFunction(obj)) {
fn = evalFn(win, obj)
}
win.describe(suiteName, fn)
})
}
const generateMochaTestsForWin = (win, obj) => {
if (typeof obj === 'function') {
win.eval(`( ${obj.toString()})()`)
return
}
createHooks(win, obj.hooks)
createTests(win, obj.tests)
createSuites(win, obj.suites)
}
const evalFn = (win, fn) => {
return function () {
return win.eval(`(${fn.toString()})`).call(this)
}
}
const cleanseRunStateMap = {
wallClockStartedAt: new Date(0),
wallClockDuration: 1,
fnDuration: 1,
afterFnDuration: 1,
lifecycle: 1,
duration: 1,
startTime: new Date(0),
'err.stack': '[err stack]',
sourceMappedStack: match.string,
parsedStack: match.array,
invocationDetails: stringifyShort,
}
const shouldHaveTestResults = (expPassed, expFailed) => {
return ({ failed }) => {
expect(failed, 'resolve with failure count').eq(failed)
expPassed = expPassed || '--'
expFailed = expFailed || '--'
cy.get('header .passed .num').should('have.text', `${expPassed}`)
cy.get('header .failed .num').should('have.text', `${expFailed}`)
}
}
const containText = (text) => {
return (($el) => {
expect($el[0]).property('innerText').contain(text)
})
}
const getRunState = (Cypress) => {
const currentRunnable = Cypress.cy.state('runnable')
const currentId = currentRunnable && currentRunnable.id
const s = {
currentId,
tests: Cypress.runner.getTestsState(),
startTime: Cypress.runner.getStartTime(),
emissions: Cypress.runner.getEmissions(),
}
s.passed = Cypress.runner.countByTestState(s.tests, 'passed')
s.failed = Cypress.runner.countByTestState(s.tests, 'failed')
s.pending = Cypress.runner.countByTestState(s.tests, 'pending')
s.numLogs = Cypress.Log.countLogsByTests(s.tests)
return _.cloneDeep(s)
}
module.exports = {
generateMochaTestsForWin,
createCypress,
containText,
cleanseRunStateMap,
shouldHaveTestResults,
getRunState,
}