-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
cy.ts
1373 lines (1087 loc) · 44.2 KB
/
cy.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
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
/* eslint-disable prefer-rest-params */
import _ from 'lodash'
import Promise from 'bluebird'
import debugFn from 'debug'
import $utils from './utils'
import $errUtils, { ErrorFromProjectRejectionEvent } from './error_utils'
import $stackUtils from './stack_utils'
import { create as createChai, IChai } from '../cy/chai'
import { create as createXhr, IXhr } from '../cy/xhrs'
import { create as createJQuery, IJQuery } from '../cy/jquery'
import { create as createAliases, IAliases } from '../cy/aliases'
import { extend as extendEvents } from './events'
import { create as createFocused, IFocused } from '../cy/focused'
import { create as createMouse, Mouse } from '../cy/mouse'
import { Keyboard } from '../cy/keyboard'
import { create as createLocation, ILocation } from '../cy/location'
import { create as createAssertions, IAssertions } from '../cy/assertions'
import { bindToListeners } from '../cy/listeners'
import { $Chainer } from './chainer'
import { create as createTimer, ITimer } from '../cy/timers'
import { create as createTimeouts, ITimeouts } from '../cy/timeouts'
import { create as createRetries, IRetries } from '../cy/retries'
import { create as createStability, IStability } from '../cy/stability'
import { create as createSnapshots, ISnapshots } from '../cy/snapshots'
import { $Command } from './command'
import { CommandQueue } from './command_queue'
import { initVideoRecorder } from '../cy/video-recorder'
import { TestConfigOverride } from '../cy/testConfigOverrides'
import { create as createOverrides, IOverrides } from '../cy/overrides'
import { historyNavigationTriggeredHashChange } from '../cy/navigation'
import { EventEmitter2 } from 'eventemitter2'
import { handleCrossOriginCookies } from '../cross-origin/events/cookies'
import { trackTopUrl } from '../util/trackTopUrl'
import type { ICypress } from '../cypress'
import type { ICookies } from './cookies'
import type { StateFunc, SubjectChain, QueryFunction } from './state'
const debugErrors = debugFn('cypress:driver:errors')
const returnedFalse = (result) => {
return result === false
}
const getContentWindow = ($autIframe) => {
return $autIframe.prop('contentWindow')
}
const setWindowDocumentProps = function (contentWindow, state) {
state('window', contentWindow)
state('document', contentWindow.document)
}
function __stackReplacementMarker (fn, ctx, args) {
return fn.apply(ctx, args)
}
declare let top: WindowProxy & { __alreadySetErrorHandlers__: boolean }
// We only set top.onerror once since we make it configurable:false
// but we update cy instance every run (page reload or rerun button)
let curCy: $Cy | null = null
const setTopOnError = function (Cypress, cy: $Cy) {
if (curCy) {
curCy = cy
return
}
curCy = cy
try {
// prevent overriding top.onerror twice when loading more than one
// instance of test runner.
if (top.__alreadySetErrorHandlers__) {
return
}
} catch (err) {
return
}
// eslint-disable-next-line @cypress/dev/arrow-body-multiline-braces
const onTopError = (handlerType) => (event) => {
const { originalErr, err, promise } = $errUtils.errorFromUncaughtEvent(handlerType, event) as ErrorFromProjectRejectionEvent
// in some callbacks like for cy.intercept, we catch the errors and then
// rethrow them, causing them to get caught by the top frame
// but they came from the spec, so we need to differentiate them
const isSpecError = $errUtils.isSpecError(Cypress.config('spec'), err)
const handled = curCy!.onUncaughtException({
err,
promise,
handlerType,
frameType: isSpecError ? 'spec' : 'app',
})
debugErrors('uncaught top error: %o', originalErr)
$errUtils.logError(Cypress, handlerType, originalErr, handled)
// return undefined so the browser does its default
// uncaught exception behavior (logging to console)
return undefined
}
top.addEventListener('error', onTopError('error'))
// prevent Mocha from setting top.onerror
Object.defineProperty(top, 'onerror', {
set () { },
get () { },
configurable: false,
enumerable: true,
})
top.addEventListener('unhandledrejection', onTopError('unhandledrejection'))
top.__alreadySetErrorHandlers__ = true
}
const ensureRunnable = (cy, cmd) => {
if (!cy.state('runnable')) {
$errUtils.throwErrByPath('miscellaneous.outside_test_with_cmd', {
args: { cmd },
})
}
}
interface ICyFocused extends Omit<
IFocused,
'documentHasFocus' | 'interceptFocus' | 'interceptBlur'
> { }
interface ICySnapshots extends Omit<
ISnapshots,
'onCssModified' | 'onBeforeWindowLoad'
> { }
export class $Cy extends EventEmitter2 implements ITimeouts, IStability, IAssertions, IRetries, IJQuery, ILocation, ITimer, IChai, IXhr, IAliases, ICySnapshots, ICyFocused {
id: string
specWindow: any
state: StateFunc
config: any
Cypress: ICypress
Cookies: ICookies
devices: {
keyboard: Keyboard
mouse: Mouse
}
queue: CommandQueue
timeout: ITimeouts['timeout']
clearTimeout: ITimeouts['clearTimeout']
isStable: IStability['isStable']
whenStable: IStability['whenStable']
assert: IAssertions['assert']
verifyUpcomingAssertions: IAssertions['verifyUpcomingAssertions']
retry: IRetries['retry']
retryIfCommandAUTOriginMismatch: IRetries['retryIfCommandAUTOriginMismatch']
$$: IJQuery['$$']
getRemotejQueryInstance: IJQuery['getRemotejQueryInstance']
getRemoteLocation: ILocation['getRemoteLocation']
getCrossOriginRemoteLocation: ILocation['getCrossOriginRemoteLocation']
fireBlur: IFocused['fireBlur']
fireFocus: IFocused['fireFocus']
needsFocus: IFocused['needsFocus']
getFocused: IFocused['getFocused']
pauseTimers: ITimer['pauseTimers']
expect: IChai['expect']
getIndexedXhrByAlias: IXhr['getIndexedXhrByAlias']
addAlias: IAliases['addAlias']
getAlias: IAliases['getAlias']
getNextAlias: IAliases['getNextAlias']
validateAlias: IAliases['validateAlias']
aliasNotFoundFor: IAliases['aliasNotFoundFor']
getXhrTypeByAlias: IAliases['getXhrTypeByAlias']
createSnapshot: ISnapshots['createSnapshot']
detachDom: ISnapshots['detachDom']
getStyles: ISnapshots['getStyles']
resetTimer: ReturnType<typeof createTimer>['reset']
overrides: IOverrides
// Private methods
onBeforeWindowLoad: ReturnType<typeof createSnapshots>['onBeforeWindowLoad']
documentHasFocus: ReturnType<typeof createFocused>['documentHasFocus']
interceptFocus: ReturnType<typeof createFocused>['interceptFocus']
interceptBlur: ReturnType<typeof createFocused>['interceptBlur']
private testConfigOverride: TestConfigOverride
private commandFns: Record<string, Function> = {}
private queryFns: Record<string, Function> = {}
constructor (specWindow: SpecWindow, Cypress: ICypress, Cookies: ICookies, state: StateFunc, config: ICypress['config']) {
super()
state('specWindow', specWindow)
this.specWindow = specWindow
this.id = _.uniqueId('cy')
this.state = state
this.config = config
this.Cypress = Cypress
this.Cookies = Cookies
initVideoRecorder(Cypress)
this.testConfigOverride = new TestConfigOverride()
// bind methods
this.isCy = this.isCy.bind(this)
this.fail = this.fail.bind(this)
this.isStopped = this.isStopped.bind(this)
this.stop = this.stop.bind(this)
this.reset = this.reset.bind(this)
this.addCommandSync = this.addCommandSync.bind(this)
this.addCommand = this.addCommand.bind(this)
this.addQuery = this.addQuery.bind(this)
this.now = this.now.bind(this)
this.onBeforeAppWindowLoad = this.onBeforeAppWindowLoad.bind(this)
this.onUncaughtException = this.onUncaughtException.bind(this)
this.setRunnable = this.setRunnable.bind(this)
this.getSubjectFromChain = this.getSubjectFromChain.bind(this)
this.setSubjectForChainer = this.setSubjectForChainer.bind(this)
this.subject = this.subject.bind(this)
this.subjectChain = this.subjectChain.bind(this)
// init traits
const timeouts = createTimeouts(state)
this.timeout = timeouts.timeout
this.clearTimeout = timeouts.clearTimeout
const stability = createStability(Cypress, state)
this.isStable = stability.isStable
this.whenStable = stability.whenStable
const assertions = createAssertions(Cypress, this)
this.assert = assertions.assert
this.verifyUpcomingAssertions = assertions.verifyUpcomingAssertions
const onFinishAssertions = function () {
return assertions.finishAssertions.apply(window, arguments as any)
}
const retries = createRetries(Cypress, state, this.timeout, this.clearTimeout, this.whenStable, onFinishAssertions)
this.retry = retries.retry
this.retryIfCommandAUTOriginMismatch = retries.retryIfCommandAUTOriginMismatch
const jquery = createJQuery(state)
this.$$ = jquery.$$
this.getRemotejQueryInstance = jquery.getRemotejQueryInstance
const location = createLocation(state)
this.getRemoteLocation = location.getRemoteLocation
this.getCrossOriginRemoteLocation = location.getCrossOriginRemoteLocation
const focused = createFocused(state)
this.fireBlur = focused.fireBlur
this.fireFocus = focused.fireFocus
this.needsFocus = focused.needsFocus
this.getFocused = focused.getFocused
this.documentHasFocus = focused.documentHasFocus
this.interceptFocus = focused.interceptFocus
this.interceptBlur = focused.interceptBlur
const keyboard = new Keyboard(state)
this.devices = {
keyboard,
mouse: createMouse(state, keyboard, focused, Cypress),
}
const timer = createTimer(Cypress)
this.pauseTimers = timer.pauseTimers
this.resetTimer = timer.reset
const { expect } = createChai!(specWindow, state, this.assert)
this.expect = expect
const xhr = createXhr(state)
this.getIndexedXhrByAlias = xhr.getIndexedXhrByAlias
const aliases = createAliases(this)
this.addAlias = aliases.addAlias
this.getAlias = aliases.getAlias
this.getNextAlias = aliases.getNextAlias
this.validateAlias = aliases.validateAlias
this.aliasNotFoundFor = aliases.aliasNotFoundFor
this.getXhrTypeByAlias = aliases.getXhrTypeByAlias
const snapshots = createSnapshots(this.$$, state)
this.createSnapshot = snapshots.createSnapshot
this.detachDom = snapshots.detachDom
this.getStyles = snapshots.getStyles
this.onBeforeWindowLoad = snapshots.onBeforeWindowLoad
this.overrides = createOverrides(state, config, focused, snapshots)
this.queue = new CommandQueue(state, stability, this)
setTopOnError(Cypress, this)
// make cy global in the specWindow
specWindow.cy = this
extendEvents(this)
Cypress.on('enqueue:command', (attrs: Cypress.EnqueuedCommandAttributes) => {
this.enqueue($Command.create(attrs))
})
// clears out any extra tabs/windows between tests
Cypress.on('test:before:run:async', () => {
return Cypress.backend('close:extra:targets')
})
if (!Cypress.isCrossOriginSpecBridge) {
trackTopUrl()
}
handleCrossOriginCookies(Cypress)
}
isCy (val) {
return (val === this) || $utils.isInstanceOf(val, $Chainer)
}
isStopped () {
return this.queue.stopped
}
fail (err, options: { async?: boolean } = {}) {
// if an onFail handler is provided, call this in its place (currently used for cross-origin support)
if (this.state('onFail')) {
return this.state('onFail')(err)
}
// this means the error has already been through this handler and caught
// again. but we don't need to run it through again, so we can re-throw
// it and it will fail the test as-is
if (err && err.hasFailed) {
delete err.hasFailed
throw err
}
options = _.defaults(options, {
async: false,
})
let rets
this.queue.stop()
if (typeof err === 'string') {
err = new Error(err)
}
err.stack = $stackUtils.normalizedStack(err)
err = $errUtils.enhanceStack({
err,
userInvocationStack: $errUtils.getUserInvocationStack(err, this.state),
projectRoot: this.config('projectRoot'),
})
err = $errUtils.processErr(err, this.config)
err.hasFailed = true
// store the error on state now
this.state('error', err)
const cy = this
const finish = function (err) {
// if the test has a (done) callback, we fail the test with that
const d = cy.state('done')
if (d) {
return d(err)
}
// if this failure was asynchronously called (outside the promise chain)
// but the promise chain is still active, reject it. if we're inside
// the promise chain, this isn't necessary and will actually mess it up
const r = cy.state('reject')
if (options.async && r) {
return r(err)
}
// we're in the promise chain, so throw the error and it will
// get caught by mocha and fail the test
throw err
}
// this means the error came from a 'fail' handler, so don't send
// 'cy:fail' action again, just finish up
if (err.isCyFailErr) {
delete err.isCyFailErr
return finish(err)
}
// if we have a "fail" handler
// 1. catch any errors it throws and fail the test
// 2. otherwise swallow any errors
// 3. but if the test is not ended with a done()
// then it should fail
// 4. and tests without a done will pass
// if we don't have a "fail" handler
// 1. callback with state("done") when async
// 2. throw the error for the promise chain
try {
this.Cypress.state('logGroupIds', []) // reset log groups so assertions are at the top level
// collect all of the callbacks for 'fail'
rets = this.Cypress.action('cy:fail', err, this.state('runnable'))
} catch (cyFailErr: any) {
// and if any of these throw synchronously immediately error
cyFailErr.isCyFailErr = true
return this.fail(cyFailErr)
}
// bail if we had callbacks attached
if (rets && rets.length) {
return
}
// else figure out how to finish this failure
return finish(err)
}
initialize ($autIframe) {
this.state('$autIframe', $autIframe)
// don't need to worry about a try/catch here
// because this is during initialize and its
// impossible something is wrong here
setWindowDocumentProps(getContentWindow($autIframe), this.state)
// initially set the content window listeners too
// so we can tap into all the normal flow of events
// like before:unload, navigation events, etc
this.contentWindowListeners(getContentWindow($autIframe))
// the load event comes from the autIframe anytime any window
// inside of it loads.
// when this happens we need to check for cross origin errors
// by trying to talk to the contentWindow document to see if
// its accessible.
// when we find ourselves in a cross origin situation, then our
// proxy has not injected Cypress.action('window:before:load')
// so Cypress.onBeforeAppWindowLoad() was never called
return $autIframe.on('load', async () => {
if (historyNavigationTriggeredHashChange(this.state)) {
// Skip load event.
// Chromium 97+ triggers fires iframe onload for cross-origin-initiated same-document
// navigations to make it appear to be a cross-document navigation, even when it wasn't
// to alleviate security risk where a cross-origin initiator can check whether
// or not onload fired to guess the url of a target frame.
// When the onload is fired, neither the before:unload or unload event is fired to remove
// the attached listeners or to clean up the current page state.
// https://github.com/cypress-io/cypress/issues/19230
return
}
// if setting these props failed then we know we're in a cross origin failure
try {
const autWindow = getContentWindow($autIframe)
let isRunnerAbleToCommunicateWithAUT: boolean
try {
// Test to see if we can communicate with the AUT.
autWindow.location.href
isRunnerAbleToCommunicateWithAUT = true
} catch (err: any) {
isRunnerAbleToCommunicateWithAUT = false
}
// If the runner can communicate, we should setup all events, otherwise just setup the window and fire the load event.
if (isRunnerAbleToCommunicateWithAUT) {
if (this.Cypress.isBrowser('webkit')) {
// WebKit's unhandledrejection event will sometimes not fire within the AUT
// due to a documented bug: https://bugs.webkit.org/show_bug.cgi?id=187822
// To ensure that the event will always fire (and always report these
// unhandled rejections to the user), we patch the AUT's Error constructor
// to enqueue a no-op microtask when executed, which ensures that the unhandledrejection
// event handler will be executed if this Error is uncaught.
const originalError = autWindow.Error
autWindow.Error = function __CyWebKitError (...args) {
autWindow.queueMicrotask(() => { })
return originalError.apply(this, args)
}
}
setWindowDocumentProps(autWindow, this.state)
// we may need to update the url now
this.urlNavigationEvent('load')
// we normally DON'T need to reapply contentWindow listeners
// because they would have been automatically applied during
// onBeforeAppWindowLoad, but in the case where we visited
// about:blank in a visit, we do need these
this.contentWindowListeners(autWindow)
} else {
this.state('window', autWindow)
this.state('document', undefined)
// we may need to update the url now
this.urlNavigationEvent('load')
}
// stability is signalled after the window:load event to give event
// listeners time to be invoked prior to moving on, but not if
// there is a cross-origin error and the cy.origin API is
// not utilized
try {
// Get the location even if we're cross origin.
const remoteLocation = await this.getCrossOriginRemoteLocation()
cy.state('autLocation', remoteLocation)
this.Cypress.action('app:window:load', this.state('window'), remoteLocation.href)
this.Cypress.primaryOriginCommunicator.toAllSpecBridges('window:load', { url: remoteLocation.href })
} catch (err: any) {
// this catches errors thrown by user-registered event handlers
// for `window:load`. this is used in the `catch` below so they
// aren't mistaken as cross-origin errors
// If this is a cypress error, pass it on through.
if (!$errUtils.isCypressErr(err)) {
err.isFromWindowLoadEvent = true
}
throw err
} finally {
this.isStable(true, 'load')
}
} catch (err: any) {
if (err.isFromWindowLoadEvent) {
delete err.isFromWindowLoadEvent
// the user's window:load handler threw an error, so propagate that
// and fail the test
const r = this.state('reject')
if (r) {
return r(err)
}
}
// we failed setting the remote window props which
// means the page navigated to a different origin
let e = err
// we failed setting the remote window props
// which means we're in a cross origin failure
// check first to see if you have a callback function
// defined and let the page load change the error
const onpl = this.state('onPageLoadErr')
if (onpl) {
e = onpl(e)
}
this.Cypress.emit('internal:window:load', {
type: 'cross:origin:failure',
error: e,
})
// need async:true since this is outside the command queue promise
// chain and cy.fail needs to know to use the reference to the
// last command to reject it
this.fail(e, { async: true })
}
})
}
stop () {
// don't do anything if we've already stopped
if (this.queue.stopped) {
return
}
return this.doneEarly()
}
// reset is called before each test
reset (test) {
try {
const s = this.state()
const backup = {
test,
window: s.window,
document: s.document,
$autIframe: s.$autIframe,
specWindow: s.specWindow,
activeSessions: s.activeSessions,
}
// reset state back to empty object
this.state.reset()
// and then restore these backed up props
this.state(backup)
this.queue.reset()
this.queue.clear()
this.resetTimer()
this.removeAllListeners()
this.testConfigOverride.restoreAndSetTestConfigOverrides(test, this.Cypress.config, this.Cypress.env)
} catch (err) {
this.fail(err)
}
}
addCommandSync (name, fn) {
const cy = this
cy[name] = function () {
return fn.apply(cy.runnableCtx(name), arguments)
}
}
runQueue () {
cy.queue.run()
}
addCommand ({ name, fn, type, prevSubject }) {
const cy = this
this.commandFns[name] = fn
const wrap = function (firstCall) {
if (type === 'parent') {
return (chainerId, ...args) => fn.apply(cy.runnableCtx(name), args)
}
const wrapped = function (chainerId, ...args) {
// push the subject into the args
if (firstCall) {
cy.validateFirstCall(name, args, prevSubject)
}
args = cy.pushSubject(name, args, prevSubject, chainerId)
return fn.apply(cy.runnableCtx(name), args)
}
wrapped.originalFn = fn
return wrapped
}
const cyFn = wrap(true)
const chainerFn = wrap(false)
const callback = (chainer, userInvocationStack, args, privilegeVerification, firstCall = false) => {
// dont enqueue / inject any new commands if
// onInjectCommand returns false
const onInjectCommand = cy.state('onInjectCommand')
if (_.isFunction(onInjectCommand) && onInjectCommand.call(cy, name, ...args) === false) {
return
}
cy.enqueue($Command.create({
name,
args,
type,
chainerId: chainer.chainerId,
userInvocationStack,
fn: firstCall ? cyFn : chainerFn,
privilegeVerification,
}))
}
$Chainer.add(name, callback)
cy[name] = function (...args) {
ensureRunnable(cy, name)
// for privileged commands, we send a message to the server that verifies
// them as coming from the spec. the fulfillment of this promise means
// the message was received. the implementation for those commands
// checks to make sure this promise is fulfilled before sending its
// websocket message for running the command to ensure prevent a race
// condition where running the command happens before the command is
// verified
const privilegeVerification = Cypress.emitMap('command:invocation', { name, args })
// this is the first call on cypress
// so create a new chainer instance
const chainer = new $Chainer(cy.specWindow)
if (cy.state('chainerId')) {
cy.linkSubject(chainer.chainerId, cy.state('chainerId'))
}
const userInvocationStack = $stackUtils.captureUserInvocationStack(cy.specWindow.Error)
callback(chainer, userInvocationStack, args, privilegeVerification, true)
// if we are in the middle of a command
// and its return value is a promise
// that means we are attempting to invoke
// a cypress command within another cypress
// command and we should error
const ret = cy.state('commandIntermediateValue')
if (ret) {
const current = cy.state('current')
// if this is a custom promise
if ($utils.isPromiseLike(ret) && $utils.noArgsAreAFunction(current.get('args'))) {
$errUtils.throwErrByPath(
'miscellaneous.command_returned_promise_and_commands', {
args: {
current: current.get('name'),
called: name,
},
},
)
}
}
// if we're the first call onto a cy
// command, then kick off the run
if (!cy.state('promise')) {
if (cy.state('returnedCustomPromise')) {
cy.warnMixingPromisesAndCommands()
}
cy.runQueue()
}
return chainer
}
}
addQuery ({ name, fn }) {
const cy = this
this.queryFns[name] = fn
const callback = (chainer, userInvocationStack, args, privilegeVerification) => {
// dont enqueue / inject any new commands if
// onInjectCommand returns false
const onInjectCommand = cy.state('onInjectCommand')
if (_.isFunction(onInjectCommand) && onInjectCommand.call(cy, name, ...args) === false) {
return
}
// Queries are functions that accept args (which is called once each time the command is used in the spec
// file), which return a function that accepts the subject (which is potentially called any number of times).
// The outer function is used to store any needed state needed by a particular instance of the command, such as
// a Cypress.log() instance, while the inner one (queryFn here) is the one that determines the next subject.
// We enqueue the outer function as the "cypress command". See command_queue.ts for details on how this is
// invoked and the inner function retried.
const command = $Command.create({
name,
args,
chainerId: chainer.chainerId,
userInvocationStack,
query: true,
})
const cyFn = function (chainerId, ...args) {
return fn.apply(command, args)
}
cyFn.originalFn = fn
command.set('fn', cyFn)
command.set('privilegeVerification', privilegeVerification)
cy.enqueue(command)
}
$Chainer.add(name, callback)
cy[name] = function (...args) {
ensureRunnable(cy, name)
// for privileged commands, we send a message to the server that verifies
// them as coming from the spec. the fulfillment of this promise means
// the message was received. the implementation for those commands
// checks to make sure this promise is fulfilled before sending its
// websocket message for running the command to ensure prevent a race
// condition where running the command happens before the command is
// verified
const privilegeVerification = Cypress.emitMap('command:invocation', { name, args })
// this is the first call on cypress
// so create a new chainer instance
const chainer = new $Chainer(cy.specWindow)
if (cy.state('chainerId')) {
cy.linkSubject(chainer.chainerId, cy.state('chainerId'))
}
const userInvocationStack = $stackUtils.captureUserInvocationStack(cy.specWindow.Error)
callback(chainer, userInvocationStack, args, privilegeVerification)
// if we're the first call onto a cy
// command, then kick off the run
if (!cy.state('promise')) {
cy.runQueue()
}
return chainer
}
}
now (name: string, ...args: any[]): Promise<any> | QueryFunction {
if (this.queryFns[name]) {
return this.queryFns[name].apply(this.state('current'), args)
}
return Promise.resolve(
this.commandFns[name].apply(this, args),
)
}
onBeforeAppWindowLoad (contentWindow) {
// we set window / document props before the window load event
// so that we properly handle events coming from the application
// from the time that happens BEFORE the load event occurs
setWindowDocumentProps(contentWindow, this.state)
this.urlNavigationEvent('before:load')
this.contentWindowListeners(contentWindow)
this.overrides.wrapNativeMethods(contentWindow)
this.onBeforeWindowLoad()
}
onUncaughtException ({ handlerType, frameType, err, promise }) {
err = $errUtils.createUncaughtException({
handlerType,
frameType,
state: this.state,
err,
})
const runnable = this.state('runnable')
// don't do anything if we don't have a current runnable
if (!runnable) return
// uncaught exceptions should be only be catchable in the AUT (app)
// or if in component testing mode, since then the spec frame and
// AUT frame are the same
if (frameType === 'app' || this.config('componentTesting')) {
try {
const results = this.Cypress.action('app:uncaught:exception', err, runnable, promise)
// dont do anything if any of our uncaught:exception
// listeners returned false
if (_.some(results, returnedFalse)) {
// return true to signal that the user handled this error
return true
}
} catch (uncaughtExceptionErr) {
err = $errUtils.createUncaughtException({
err: uncaughtExceptionErr,
handlerType: 'error',
frameType: 'spec',
state: this.state,
})
}
}
try {
this.fail(err)
} catch (failErr) {
const r = this.state('reject')
if (r) {
r(err)
}
}
return
}
setRunnable (runnable, hookId) {
// when we're setting a new runnable
// prepare to run again!
this.queue.reset()
// reset the promise again
this.state('promise', undefined)
this.state('hookId', hookId)
this.state('runnable', runnable)
this.state('ctx', runnable.ctx)
const { fn } = runnable
const restore = () => {
return runnable.fn = fn
}
const cy = this
runnable.fn = function () {
restore()
const timeout = cy.config('defaultCommandTimeout')
// control timeouts on runnables ourselves
if (_.isFinite(timeout)) {
cy.timeout(timeout)
}
// store the current length of our queue
// before we invoke the runnable.fn
const currentLength = cy.queue.length
try {
// if we have a fn.length that means we
// are accepting a done callback and need
// to change the semantics around how we
// attach the run queue
let done
if (fn.length) {
const originalDone = arguments[0]
arguments[0] = (done = function (err) {
// TODO: handle no longer error when ended early
cy.doneEarly()
originalDone(err)
// return null else we there are situations
// where returning a regular bluebird promise
// results in a warning about promise being created
// in a handler but not returned
return null
})
// store this done property
// for async tests
cy.state('done', done)
}
let ret = __stackReplacementMarker(fn, this, arguments)
// if we returned a value from fn
// and enqueued some new commands
// and the value isn't currently cy
// or a promise
if (ret &&
cy.queue.length > currentLength &&
!cy.isCy(ret) &&
!$utils.isPromiseLike(ret)) {
// TODO: clean this up in the utility function