forked from cypress-io/cypress
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcypress_spec.js
1949 lines (1638 loc) · 62.6 KB
/
cypress_spec.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
/* eslint-disable no-console */
/*global globalThis*/
require('../spec_helper')
const _ = require('lodash')
const path = require('path')
const EE = require('events')
const http = require('http')
const Promise = require('bluebird')
const electron = require('electron')
const commitInfo = require('@cypress/commit-info')
const Fixtures = require('@tooling/system-tests')
const { normalizeStdout } = require('@tooling/system-tests/lib/normalizeStdout')
const snapshot = require('snap-shot-it')
const stripAnsi = require('strip-ansi')
const pkg = require('@packages/root')
const detect = require('@packages/launcher/lib/detect')
const launch = require('@packages/launcher/lib/browsers')
const extension = require('@packages/extension')
const { validation: v } = require('@packages/config')
const argsUtil = require(`../../lib/util/args`)
const { fs } = require(`../../lib/util/fs`)
const ciProvider = require(`../../lib/util/ci_provider`)
const settings = require(`../../lib/util/settings`)
const Windows = require(`../../lib/gui/windows`)
const interactiveMode = require(`../../lib/modes/interactive`)
const api = require(`../../lib/cloud/api`).default
const cwd = require(`../../lib/cwd`)
const user = require(`../../lib/cloud/user`)
const cache = require(`../../lib/cache`)
const errors = require(`../../lib/errors`)
const cypress = require(`../../lib/cypress`)
const ProjectBase = require(`../../lib/project-base`).ProjectBase
const { ServerBase } = require(`../../lib/server-base`)
const Reporter = require(`../../lib/reporter`)
const browsers = require(`../../lib/browsers`)
const videoCapture = require(`../../lib/video_capture`)
const browserUtils = require(`../../lib/browsers/utils`)
const chromeBrowser = require(`../../lib/browsers/chrome`)
const { openProject } = require(`../../lib/open_project`)
const env = require(`../../lib/util/env`)
const system = require(`../../lib/util/system`)
const appData = require(`../../lib/util/app_data`)
const electronApp = require('../../lib/util/electron-app')
const savedState = require(`../../lib/saved_state`)
const { getCtx, clearCtx, setCtx, makeDataContext } = require(`../../lib/makeDataContext`)
const { BrowserCriClient } = require(`../../lib/browsers/browser-cri-client`)
const { cloudRecommendationMessage } = require('../../lib/util/print-run')
const processVersions = process.versions
const TYPICAL_BROWSERS = [
{
name: 'chrome',
family: 'chromium',
channel: 'stable',
displayName: 'Chrome',
version: '60.0.3112.101',
path: '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
majorVersion: '60',
}, {
name: 'chromium',
family: 'chromium',
channel: 'stable',
displayName: 'Chromium',
version: '49.0.2609.0',
path: '/Users/bmann/Downloads/chrome-mac/Chromium.app/Contents/MacOS/Chromium',
majorVersion: '49',
}, {
name: 'chrome',
family: 'chromium',
channel: 'canary',
displayName: 'Canary',
version: '62.0.3197.0',
path: '/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary',
majorVersion: '62',
},
]
const ELECTRON_BROWSER = {
name: 'electron',
family: 'chromium',
displayName: 'Electron',
path: '',
version: '99.101.1234',
majorVersion: 99,
}
const previousCwd = process.cwd()
const snapshotConsoleLogs = function (name) {
const args = _
.chain(console.log.args)
.map((innerArgs) => {
return innerArgs.join(' ')
}).join('\n')
.value()
// our cwd() is currently the project
// so must switch back to original
process.chdir(previousCwd)
const snap = normalizeStdout(stripAnsi(args))
return snapshot(name, snap)
}
function mockEE () {
const ee = new EE()
ee.kill = () => {
// ughh, would be nice to test logic inside the launcher
// that cleans up after the browser exit
// like calling client.close() if available to let the
// browser free any resources
return ee.emit('exit')
}
ee.destroy = () => {
return ee.emit('closed')
}
ee.isDestroyed = () => {
return false
}
ee.loadURL = () => {}
ee.focusOnWebView = () => {}
ee.webContents = {
getOSProcessId: sinon.stub(),
setUserAgent: sinon.stub(),
session: {
clearCache: sinon.stub().resolves(),
setProxy: sinon.stub().resolves(),
setUserAgent: sinon.stub(),
on: sinon.stub(),
removeListener: sinon.stub(),
webRequest: {
onBeforeSendHeaders () {},
},
},
}
ee.maximize = sinon.stub
ee.setSize = sinon.stub
return ee
}
let ctx
describe('lib/cypress', () => {
require('mocha-banner').register()
beforeEach(async function () {
ctx = getCtx()
process.chdir(previousCwd)
this.timeout(8000)
await cache.remove()
Fixtures.scaffold()
this.todosPath = Fixtures.projectPath('todos')
this.pristinePath = Fixtures.projectPath('pristine')
this.pristineWithConfigPath = Fixtures.projectPath('pristine-with-e2e-testing')
this.noScaffolding = Fixtures.projectPath('no-scaffolding')
this.recordPath = Fixtures.projectPath('record')
this.pluginConfig = Fixtures.projectPath('plugin-config')
this.pluginBrowser = Fixtures.projectPath('plugin-browser')
this.idsPath = Fixtures.projectPath('ids')
// force cypress to call directly into main without
// spawning a separate process
sinon.stub(videoCapture, 'start').resolves({})
sinon.stub(electronApp, 'isRunning').returns(true)
sinon.stub(extension, 'setHostAndPath').resolves()
sinon.stub(detect, 'detect').resolves([...TYPICAL_BROWSERS])
sinon.stub(process, 'exit')
sinon.stub(ServerBase.prototype, 'reset')
sinon.stub(errors, 'warning')
.callThrough()
.withArgs('INVOKED_BINARY_OUTSIDE_NPM_MODULE')
.returns(null)
sinon.spy(errors, 'log')
sinon.spy(errors, 'logException')
sinon.spy(console, 'log')
// to make sure our Electron browser mock object passes validation during tests
sinon.stub(process, 'versions').value({
...processVersions,
chrome: ELECTRON_BROWSER.version,
electron: '123.45.6789',
})
this.expectExitWith = (code) => {
expect(process.exit).to.be.calledWith(code)
}
// returns error object
this.expectExitWithErr = (type, msg1, msg2) => {
expect(errors.log, 'error was logged').to.be.calledWithMatch({ type })
expect(process.exit, 'process.exit was called').to.be.calledWith(1)
const err = errors.log.getCall(0).args[0]
if (msg1) {
expect(stripAnsi(err.message), 'error text').to.include(msg1)
}
if (msg2) {
expect(stripAnsi(err.message), 'second error text').to.include(msg2)
}
return err
}
})
afterEach(async () => {
try {
// make sure every project
// we spawn is closed down
await openProject.close()
} catch (e) {
// ...
}
Fixtures.remove()
delete globalThis['CY_TEST_MOCK']
})
context('test browsers', () => {
// sanity checks to make sure the browser objects we pass during tests
// all pass the internal validation function
it('has valid browsers', () => {
expect(v.isValidBrowserList('browsers', TYPICAL_BROWSERS)).to.be.true
})
it('has valid electron browser', () => {
expect(v.isValidBrowserList('browsers', [ELECTRON_BROWSER])).to.be.true
})
it('allows browser major to be a number', () => {
const browser = {
name: 'Edge Beta',
family: 'chromium',
displayName: 'Edge Beta',
version: '80.0.328.2',
path: '/some/path',
majorVersion: 80,
}
expect(v.isValidBrowserList('browsers', [browser])).to.be.true
})
it('validates returned list', () => {
return browserUtils.getBrowsers().then((list) => {
expect(v.isValidBrowserList('browsers', list)).to.be.true
})
})
})
context('error handling', function () {
it('exits if config cannot be parsed', function () {
return cypress.start(['--config', 'xyz'])
.then(() => {
const err = this.expectExitWithErr('COULD_NOT_PARSE_ARGUMENTS')
snapshot('could not parse config error', stripAnsi(err.message))
})
})
it('exits if env cannot be parsed', function () {
return cypress.start(['--env', 'a123'])
.then(() => {
const err = this.expectExitWithErr('COULD_NOT_PARSE_ARGUMENTS')
snapshot('could not parse env error', stripAnsi(err.message))
})
})
it('exits if reporter options cannot be parsed', function () {
return cypress.start(['--reporterOptions', 'nonono'])
.then(() => {
const err = this.expectExitWithErr('COULD_NOT_PARSE_ARGUMENTS')
snapshot('could not parse reporter options error', stripAnsi(err.message))
})
})
})
context('invalid config', function () {
beforeEach(async function () {
this.win = {
on: sinon.stub(),
webContents: {
on: sinon.stub(),
},
}
await clearCtx()
sinon.stub(electron.app, 'on').withArgs('ready').yieldsAsync()
sinon.stub(Windows, 'open').resolves(this.win)
})
it('shows warning if config is not valid', function () {
return cypress.start(['--config=test=false', '--cwd=/foo/bar'])
.then(() => {
expect(errors.warning).to.be.calledWith('INVALID_CONFIG_OPTION')
expect(console.log).to.be.calledWithMatch('The following configuration option is invalid:')
expect(console.log).to.be.calledWithMatch(`test`)
expect(console.log).to.be.calledWithMatch('https://on.cypress.io/configuration')
})
})
it('shows warning when multiple config are not valid', function () {
return cypress.start(['--config=test=false,foo=bar', '--cwd=/foo/bar'])
.then(() => {
expect(errors.warning).to.be.calledWith('INVALID_CONFIG_OPTION')
expect(console.log).to.be.calledWithMatch('The following configuration options are invalid:')
expect(console.log).to.be.calledWithMatch('test')
expect(console.log).to.be.calledWithMatch('foo')
expect(console.log).to.be.calledWithMatch('https://on.cypress.io/configuration')
snapshotConsoleLogs('INVALID_CONFIG_OPTION')
})
})
it('does not show warning if config is valid', function () {
return cypress.start(['--config=trashAssetsBeforeRuns=false'])
.then(() => {
expect(errors.warning).to.not.be.calledWith('INVALID_CONFIG_OPTION')
})
})
})
context('--run-project', () => {
beforeEach(async () => {
await clearCtx()
sinon.stub(electron.app, 'on').withArgs('ready').yieldsAsync()
globalThis.CY_TEST_MOCK = {
waitForSocketConnection: true,
listenForProjectEnd: { stats: { failures: 0 } },
}
sinon.stub(browsers, 'open')
sinon.stub(browsers, 'connectToNewSpec')
sinon.stub(commitInfo, 'getRemoteOrigin').resolves('remoteOrigin')
})
describe('cloud recommendation message', () => {
it('gets logged when in CI and there is a failure', function () {
const relativePath = path.relative(cwd(), this.todosPath)
sinon.stub(ciProvider, 'getIsCi').returns(true)
delete process.env.CYPRESS_COMMERCIAL_RECOMMENDATIONS
globalThis.CY_TEST_MOCK.listenForProjectEnd = { stats: { failures: 1 } }
return cypress.start([`--run-project=${this.todosPath}`, `--spec=${relativePath}/tests/test1.js`]).then(() => {
expect(console.log).to.be.calledWith(cloudRecommendationMessage)
snapshotConsoleLogs('CLOUD_RECOMMENDATION_MESSAGE')
})
})
it('does not get logged if CYPRESS_COMMERCIAL_RECOMMENDATIONS is set to 0', function () {
const relativePath = path.relative(cwd(), this.todosPath)
sinon.stub(ciProvider, 'getIsCi').returns(true)
process.env.CYPRESS_COMMERCIAL_RECOMMENDATIONS = '0'
globalThis.CY_TEST_MOCK.listenForProjectEnd = { stats: { failures: 1 } }
return cypress.start([`--run-project=${this.todosPath}`, `--spec=${relativePath}/tests/test1.js`]).then(() => {
expect(console.log).not.to.be.calledWith(cloudRecommendationMessage)
})
})
it('does not get logged if all tests pass', function () {
const relativePath = path.relative(cwd(), this.todosPath)
sinon.stub(ciProvider, 'getIsCi').returns(true)
delete process.env.CYPRESS_COMMERCIAL_RECOMMENDATIONS
globalThis.CY_TEST_MOCK.listenForProjectEnd = { stats: { failures: 0 } }
return cypress.start([`--run-project=${this.todosPath}`, `--spec=${relativePath}/tests/test1.js`]).then(() => {
expect(console.log).not.to.be.calledWith(cloudRecommendationMessage)
})
})
it('does not get logged if not running in CI', function () {
const relativePath = path.relative(cwd(), this.todosPath)
sinon.stub(ciProvider, 'getIsCi').returns(undefined)
delete process.env.CYPRESS_COMMERCIAL_RECOMMENDATIONS
globalThis.CY_TEST_MOCK.listenForProjectEnd = { stats: { failures: 1 } }
return cypress.start([`--run-project=${this.todosPath}`, `--spec=${relativePath}/tests/test1.js`]).then(() => {
expect(console.log).not.to.be.calledWith(cloudRecommendationMessage)
})
})
})
it('runs project headlessly and exits with exit code 0', function () {
return cypress.start([`--run-project=${this.todosPath}`])
.then(() => {
expect(browsers.open).to.be.calledWithMatch(ELECTRON_BROWSER)
this.expectExitWith(0)
})
})
it('sets --headed false if --headless', function () {
sinon.spy(cypress, 'startInMode')
return cypress.start([`--run-project=${this.todosPath}`, '--headless'])
.then(() => {
expect(browsers.open).to.be.calledWithMatch(ELECTRON_BROWSER)
this.expectExitWith(0)
// check how --headless option sets --headed
expect(cypress.startInMode).to.be.calledOnce
expect(cypress.startInMode).to.be.calledWith('run')
const startInModeOptions = cypress.startInMode.firstCall.args[1]
expect(startInModeOptions).to.include({
headless: true,
headed: false,
})
})
})
it('throws an error if both --headed and --headless are true', function () {
// error is thrown synchronously
expect(() => cypress.start([`--run-project=${this.todosPath}`, '--headless', '--headed']))
.to.throw('Impossible options: both headless and headed are true')
})
describe('strips --', () => {
beforeEach(() => {
sinon.spy(argsUtil, 'toObject')
})
it('strips leading', function () {
return cypress.start(['--', `--run-project=${this.todosPath}`])
.then(() => {
expect(argsUtil.toObject).to.have.been.calledWith([`--run-project=${this.todosPath}`])
expect(browsers.open).to.be.calledWithMatch(ELECTRON_BROWSER)
this.expectExitWith(0)
})
})
it('strips in the middle', function () {
return cypress.start([`--run-project=${this.todosPath}`, '--', '--browser=electron'])
.then(() => {
expect(argsUtil.toObject).to.have.been.calledWith([`--run-project=${this.todosPath}`, '--browser=electron'])
expect(browsers.open).to.be.calledWithMatch(ELECTRON_BROWSER)
this.expectExitWith(0)
})
})
})
it('runs project headlessly and exits with exit code 10', function () {
globalThis.CY_TEST_MOCK.runSpecs = { totalFailed: 10 }
return cypress.start([`--run-project=${this.todosPath}`])
.then(() => {
this.expectExitWith(10)
})
})
it('does not add project to the global cache', function () {
return cache.getProjectRoots()
.then((projects) => {
// no projects in the cache
expect(projects.length).to.eq(0)
return cypress.start([`--run-project=${this.todosPath}`])
}).then(() => {
return cache.getProjectRoots()
}).then((projects) => {
// still not projects
expect(projects.length).to.eq(0)
})
})
it('runs project by relative spec and exits with status 0', function () {
const relativePath = path.relative(cwd(), this.todosPath)
return cypress.start([
`--run-project=${this.todosPath}`,
`--spec=${relativePath}/tests/test2.coffee`,
])
.then(() => {
expect(browsers.open).to.be.calledWithMatch(ELECTRON_BROWSER, {
url: 'http://localhost:8888/__/#/specs/runner?file=tests/test2.coffee',
})
this.expectExitWith(0)
})
})
it('runs project by specific spec with default configuration', function () {
return cypress.start([`--run-project=${this.idsPath}`, `--spec=${this.idsPath}/**/*qux*`, '--config', 'port=2020'])
.then(() => {
expect(browsers.open).to.be.calledWithMatch(ELECTRON_BROWSER, { url: 'http://localhost:2020/__/#/specs/runner?file=cypress/e2e/qux.cy.js' })
expect(browsers.open).to.be.calledOnce
this.expectExitWith(0)
})
})
it('runs project by specific absolute spec and exits with status 0', function () {
return cypress.start([`--run-project=${this.todosPath}`, `--spec=${this.todosPath}/tests/test2.coffee`])
.then(() => {
expect(browsers.open).to.be.calledWithMatch(ELECTRON_BROWSER, { url: 'http://localhost:8888/__/#/specs/runner?file=tests/test2.coffee' })
this.expectExitWith(0)
})
})
it('runs project by limiting spec files via config.e2e.specPattern string glob pattern', function () {
return cypress.start([`--run-project=${this.todosPath}`, `--config={"e2e":{"specPattern":"${this.todosPath}/tests/test2.coffee"}}`])
.then(() => {
expect(browsers.open).to.be.calledWithMatch(ELECTRON_BROWSER, { url: 'http://localhost:8888/__/#/specs/runner?file=tests/test2.coffee' })
this.expectExitWith(0)
})
})
it('runs project by limiting spec files via config.e2e.specPattern as a JSON array of string glob patterns', function () {
return cypress.start([`--run-project=${this.todosPath}`, '--config={"e2e":{"specPattern":["**/test2.coffee","**/test1.js"]}}'])
.then(() => {
expect(browsers.open).to.be.calledWithMatch(ELECTRON_BROWSER, { url: 'http://localhost:8888/__/#/specs/runner?file=tests/test2.coffee' })
}).then(() => {
expect(browsers.open).to.be.calledWithMatch(ELECTRON_BROWSER, { url: 'http://localhost:8888/__/#/specs/runner?file=tests/test1.js' })
this.expectExitWith(0)
})
})
it('does not scaffold when headless and exits with error when no existing project', function () {
const ensureDoesNotExist = function (inspection, index) {
if (!inspection.isRejected()) {
throw new Error(`File or folder was scaffolded at index: ${index}`)
}
expect(inspection.reason()).to.have.property('code', 'ENOENT')
}
return Promise.all([
fs.statAsync(path.join(this.pristinePath, 'cypress')).reflect(),
fs.statAsync(path.join(this.pristinePath, 'cypress.config.js')).reflect(),
])
.each(ensureDoesNotExist).then(() => {
return cypress.start([`--run-project=${this.pristinePath}`])
}).then(() => {
return Promise.all([
fs.statAsync(path.join(this.pristinePath, 'cypress')).reflect(),
fs.statAsync(path.join(this.pristinePath, 'cypress.config.js')).reflect(),
])
})
})
it('runs project headed and displays gui', function () {
return cypress.start([`--run-project=${this.todosPath}`, '--headed'])
.then(() => {
expect(browsers.open).to.be.calledWithMatch(ELECTRON_BROWSER, {
proxyServer: 'http://localhost:8888',
browser: {
isHeadless: false,
},
})
this.expectExitWith(0)
})
})
it('turns on reporting', function () {
sinon.spy(Reporter, 'create')
return cypress.start([`--run-project=${this.todosPath}`])
.then(() => {
expect(Reporter.create).to.be.calledWith('spec')
this.expectExitWith(0)
})
})
it('can change the reporter to nyan', function () {
sinon.spy(Reporter, 'create')
return cypress.start([`--run-project=${this.todosPath}`, '--reporter=nyan'])
.then(() => {
expect(Reporter.create).to.be.calledWith('nyan')
this.expectExitWith(0)
})
})
it('can change the reporter with cypress.config.js', async function () {
sinon.spy(Reporter, 'create')
return cypress.start([`--run-project=${this.idsPath}`, `--config-file=${this.idsPath}/cypress.dot-reporter.config.js`])
.then(() => {
expect(Reporter.create).to.be.calledWith('dot')
this.expectExitWith(0)
})
})
it('runs tests even when user isn\'t logged in', function () {
return user.set({})
.then(() => {
return cypress.start([`--run-project=${this.todosPath}`])
}).then(() => {
this.expectExitWith(0)
})
})
it('logs warning when projectId and key but no record option', function () {
return cypress.start([`--run-project=${this.todosPath}`, '--key=asdf'])
.then(() => {
expect(errors.warning).to.be.calledWith('PROJECT_ID_AND_KEY_BUT_MISSING_RECORD_OPTION', 'abc123')
expect(console.log).to.be.calledWithMatch('You also provided your Record Key, but you did not pass the')
expect(console.log).to.be.calledWithMatch('cypress run --record')
expect(console.log).to.be.calledWithMatch('https://on.cypress.io/recording-project-runs')
})
})
it('logs warning when removing old browser profiles fails', function () {
const err = new Error('foo')
sinon.stub(browsers, 'removeOldProfiles').rejects(err)
return cypress.start([`--run-project=${this.todosPath}`])
.then(() => {
expect(errors.warning).to.be.calledWith('CANNOT_REMOVE_OLD_BROWSER_PROFILES', err)
expect(console.log).to.be.calledWithMatch('Warning: We failed to remove old browser profiles from previous runs.')
expect(console.log).to.be.calledWithMatch(err.message)
})
})
it('does not log warning when no projectId', function () {
return cypress.start([`--run-project=${this.pristinePath}`, '--key=asdf'])
.then(() => {
expect(errors.warning).not.to.be.calledWith('PROJECT_ID_AND_KEY_BUT_MISSING_RECORD_OPTION', 'abc123')
expect(console.log).not.to.be.calledWithMatch('cypress run --key <record_key>')
})
})
it('does not log warning when projectId but --record false', function () {
return cypress.start([`--run-project=${this.todosPath}`, '--key=asdf', '--record=false'])
.then(() => {
expect(errors.warning).not.to.be.calledWith('PROJECT_ID_AND_KEY_BUT_MISSING_RECORD_OPTION', 'abc123')
expect(console.log).not.to.be.calledWithMatch('cypress run --key <record_key>')
})
})
it(`logs error when supportFile doesn't exist`, function () {
return settings.writeForTesting(this.idsPath, { e2e: { supportFile: '/does/not/exist' } })
.then(() => {
return cypress.start([`--run-project=${this.idsPath}`])
})
.then(() => {
this.expectExitWithErr('SUPPORT_FILE_NOT_FOUND', `Your supportFile is missing or invalid: /does/not/exist`)
})
})
it('logs error when browser cannot be found', function () {
browsers.open.restore()
return cypress.start([`--run-project=${this.idsPath}`, '--browser=foo'])
.then(() => {
this.expectExitWithErr('BROWSER_NOT_FOUND_BY_NAME')
// get all the error args
const argsSet = errors.log.args
const found1 = _.find(argsSet, (args) => {
return _.find(args, (arg) => {
return arg.message && stripAnsi(arg.message).includes(
`Browser: foo was not found on your system or is not supported by Cypress.`,
)
})
})
expect(found1, `foo should not be found`).to.be.ok
const found2 = _.find(argsSet, (args) => {
return _.find(args, (arg) => {
return arg.message && stripAnsi(arg.message).includes(
'Cypress supports the following browsers:',
)
})
})
expect(found2, 'supported browsers should be listed').to.be.ok
const found3 = _.find(argsSet, (args) => {
return _.find(args, (arg) => {
return arg.message && stripAnsi(arg.message).includes(
'Available browsers found on your system are:\n - chrome\n - chromium\n - chrome:canary\n - electron',
)
})
})
expect(found3, 'browser names should be listed').to.be.ok
})
})
describe('no specs found', function () {
it('logs error and exits when spec file was specified and does not exist', function () {
const cwd = process.cwd()
return cypress.start([
`--cwd=${cwd}`,
`--run-project=${this.todosPath}`,
'--spec=path/to/spec',
])
.then(() => {
// includes the search spec
this.expectExitWithErr('NO_SPECS_FOUND', 'We searched for specs matching this glob pattern:')
// includes the project path
this.expectExitWithErr('NO_SPECS_FOUND', path.join(cwd, 'path/to/spec'))
})
})
it('logs error and exits when spec file was specified and does not exist using ../ pattern', function () {
const cwd = process.cwd()
return cypress.start([
`--cwd=${cwd}`,
`--run-project=${this.todosPath}`,
'--spec=../path/to/spec',
])
.then(() => {
// includes the search spec
this.expectExitWithErr('NO_SPECS_FOUND', 'We searched for specs matching this glob pattern:')
// includes the project path
this.expectExitWithErr('NO_SPECS_FOUND', path.join(cwd, '../path/to/spec'))
})
})
it('logs error and exits when spec file was specified with glob and does not exist using ../ pattern', function () {
const cwd = process.cwd()
return cypress.start([
`--cwd=${cwd}`,
`--run-project=${this.todosPath}`,
'--spec=../path/to/**/*',
])
.then(() => {
// includes the search spec
this.expectExitWithErr('NO_SPECS_FOUND', 'We searched for specs matching this glob pattern:')
// includes the project path
this.expectExitWithErr('NO_SPECS_FOUND', path.join(cwd, '../path/to/**/*'))
})
})
it('logs error and exits when spec absolute file was specified and does not exist', function () {
return cypress.start([
`--run-project=${this.todosPath}`,
`--spec=/path/to/spec`,
])
.then(() => {
// includes folder name + path to the spec
this.expectExitWithErr('NO_SPECS_FOUND', `/path/to/spec`)
expect(errors.log).not.to.be.calledWithMatch(this.todospath)
})
})
it('logs error and exits when no specs were found at all', function () {
return cypress.start([
`--run-project=${this.todosPath}`,
'--spec=/this/does/not/exist/**/*',
])
.then(() => {
this.expectExitWithErr('NO_SPECS_FOUND', 'We searched for specs matching this glob pattern')
this.expectExitWithErr('NO_SPECS_FOUND', 'this/does/not/exist/**/*')
})
})
})
it('logs error and exits when project has cypress.config.js syntax error', function () {
return fs.writeFileAsync(`${this.todosPath}/cypress.config.js`, `module.exports = {`)
.then(() => {
return cypress.start([`--run-project=${this.todosPath}`])
}).then(() => {
this.expectExitWithErr('CONFIG_FILE_REQUIRE_ERROR', this.todosPath)
})
})
it('logs error and exits when project has cypress.env.json syntax error', function () {
return fs.writeFileAsync(`${this.todosPath}/cypress.env.json`, '{\'foo\': \'bar}')
.then(() => {
return cypress.start([`--run-project=${this.todosPath}`])
}).then(() => {
this.expectExitWithErr('ERROR_READING_FILE', this.todosPath)
})
})
it('logs error and exits when project has invalid cypress.config.js values', function () {
return settings.writeForTesting(this.todosPath, { baseUrl: 'localhost:9999' })
.then(() => {
return cypress.start([`--run-project=${this.todosPath}`])
}).then(() => {
this.expectExitWithErr('CONFIG_VALIDATION_ERROR', 'cypress.config.js')
})
})
it('logs error and exits when project has invalid config values from the CLI', function () {
return cypress.start([
`--run-project=${this.todosPath}`,
'--config=baseUrl=localhost:9999',
])
.then(() => {
this.expectExitWithErr('CONFIG_VALIDATION_ERROR', 'localhost:9999')
this.expectExitWithErr('CONFIG_VALIDATION_ERROR', 'An invalid configuration value was set.')
})
})
it('logs error and exits when project has invalid config values from env vars', function () {
process.env.CYPRESS_BASE_URL = 'localhost:9999'
return cypress.start([`--run-project=${this.todosPath}`])
.then(() => {
this.expectExitWithErr('CONFIG_VALIDATION_ERROR', 'localhost:9999')
this.expectExitWithErr('CONFIG_VALIDATION_ERROR', 'An invalid configuration value was set.')
})
})
const renamedConfigs = [
{
old: 'blacklistHosts',
new: 'blockHosts',
},
]
renamedConfigs.forEach(function (config) {
it(`logs error and exits when using an old configuration option: ${config.old}`, function () {
return cypress.start([
`--run-project=${this.todosPath}`,
`--config=${config.old}=''`,
])
.then(() => {
this.expectExitWithErr('RENAMED_CONFIG_OPTION', config.old)
this.expectExitWithErr('RENAMED_CONFIG_OPTION', config.new)
})
})
})
// TODO: make sure we have integration tests around this
// for headed projects!
// also make sure we test the rest of the integration functionality
// for headed errors! <-- not unit tests, but integration tests!
it('logs error and exits when project folder has read permissions only and cannot write cypress.config.js', function () {
// test disabled if running as root (such as inside docker) - root can write all things at all times
if (process.geteuid() === 0) {
return
}
const permissionsPath = path.resolve('./permissions')
const cypressConfig = path.join(permissionsPath, 'cypress.config.js')
return fs.mkdirAsync(permissionsPath)
.then(() => {
return fs.outputFileAsync(cypressConfig, 'module.exports = { e2e: { supportFile: false } }')
}).then(() => {
// read only
return fs.chmodAsync(permissionsPath, '555')
}).then(() => {
return cypress.start([`--run-project=${permissionsPath}`])
}).then(() => {
return fs.chmodAsync(permissionsPath, '777')
}).then(() => {
this.expectExitWithErr('ERROR_WRITING_FILE', permissionsPath)
}).finally(() => {
return fs.rmdir(permissionsPath, { recursive: true })
})
})
it('logs error and exits when reporter does not exist', function () {
return cypress.start([`--run-project=${this.todosPath}`, '--reporter', 'foobarbaz'])
.then(() => {
this.expectExitWithErr('INVALID_REPORTER_NAME', 'foobarbaz')
})
})
describe('state', () => {
beforeEach(function () {
return appData.remove()
.then(() => {
return savedState.formStatePath(this.todosPath)
}).then((statePathStart) => {
this.statePath = appData.projectsPath(statePathStart)
})
})
it('does not save project state', function () {
return cypress.start([`--run-project=${this.todosPath}`, `--spec=${this.todosPath}/tests/test2.coffee`])
.then(() => {
this.expectExitWith(0)
// this should not save the project's state
// because its a noop in 'cypress run' mode
return openProject.getProject().saveState()
}).then(() => {
return fs.statAsync(this.statePath)
.then(() => {
throw new Error(`saved state should not exist but it did here: ${this.statePath}`)
}).catch({ code: 'ENOENT' }, () => {})
})
})
})
describe('morgan', () => {
it('sets morgan to false', function () {
return cypress.start([`--run-project=${this.todosPath}`])
.then(() => {
expect(openProject.getProject().cfg.morgan).to.be.false
this.expectExitWith(0)
})
})
})
describe('config overrides', () => {
beforeEach(function () {
delete process.env.CYPRESS_COMMERCIAL_RECOMMENDATIONS
})
it('can override default values', function () {
return cypress.start([`--run-project=${this.todosPath}`, '--config=requestTimeout=1234,videoCompression=true'])
.then(() => {
const { cfg } = openProject.getProject()
expect(cfg.videoCompression).to.be.true
expect(cfg.requestTimeout).to.eq(1234)
expect(cfg.resolved.videoCompression).to.deep.eq({
value: true,
from: 'cli',
})
expect(cfg.resolved.requestTimeout).to.deep.eq({
value: 1234,
from: 'cli',
})
this.expectExitWith(0)
})
})
it('can override values in plugins', function () {
return cypress.start([
`--run-project=${this.pluginConfig}`, '--config=requestTimeout=1234,videoCompression=true',
'--env=foo=foo,bar=bar',
])
.then(() => {
const { cfg } = openProject.getProject()
expect(cfg.videoCompression).to.eq(20)
expect(cfg.defaultCommandTimeout).to.eq(500)
expect(cfg.env).to.deep.eq({
foo: 'bar',
bar: 'bar',
})
expect(cfg.resolved.videoCompression).to.deep.eq({
value: 20,
from: 'plugin',
})
expect(cfg.resolved.requestTimeout).to.deep.eq({
value: 1234,
from: 'cli',
})
expect(cfg.resolved.env.foo).to.deep.eq({
value: 'bar',
from: 'plugin',
})
expect(cfg.resolved.env.bar).to.deep.eq({
value: 'bar',
from: 'cli',
})
this.expectExitWith(0)
})
})
})
describe('plugins', () => {
beforeEach(() => {
browsers.open.restore()
const ee = mockEE()
sinon.stub(launch, 'launch').returns(ee)
sinon.stub(Windows, 'create').returns(ee)
})
context('before:browser:launch', () => {
it('chrome', function () {
// during testing, do not try to connect to the remote interface or
// use the Chrome remote interface client
const criClient = {