-
Notifications
You must be signed in to change notification settings - Fork 661
/
runner-test.js
1647 lines (1360 loc) · 65.9 KB
/
runner-test.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 */
const path = require('path');
const { expect } = require('chai');
const fs = require('fs');
const del = require('del');
const request = require('request');
const { times, uniqBy } = require('lodash');
const consoleWrapper = require('./helpers/console-wrapper');
const isAlpine = require('./helpers/is-alpine');
const createTestCafe = require('../../lib/');
const COMMAND = require('../../lib/browser/connection/command');
const Task = require('../../lib/runner/task');
const BrowserConnection = require('../../lib/browser/connection');
const browserProviderPool = require('../../lib/browser/provider/pool');
const delay = require('../../lib/utils/delay');
const OptionNames = require('../../lib/configuration/option-names');
const { GeneralError } = require('../../lib/errors/runtime');
const { RUNTIME_ERRORS } = require('../../lib/errors/types');
const { createReporter } = require('../functional/utils/reporter');
const proxyquire = require('proxyquire');
const BrowserConnectionStatus = require('../../lib/browser/connection/status');
const { noop } = require('lodash');
const Test = require('../../lib/api/structure/test');
const TestCafeConfiguration = require('../../lib/configuration/testcafe-configuration');
const createConfigFile = (configPath, options) => {
options = options || {};
fs.writeFileSync(configPath, JSON.stringify(options));
};
describe('Runner', () => {
let testCafe = null;
let runner = null;
let connection = null;
let origRemoteBrowserProvider = null;
const BROWSER_NAME = `${isAlpine() ? 'chromium' : 'chrome'}:headless`;
const remoteBrowserProviderMock = {
openBrowser () {
return Promise.resolve();
},
closeBrowser () {
return Promise.resolve();
},
};
before(() => {
return createTestCafe('127.0.0.1', 1335, 1336)
.then(tc => {
testCafe = tc;
return browserProviderPool.getProvider('remote');
})
.then(remoteBrowserProvider => {
origRemoteBrowserProvider = remoteBrowserProvider;
browserProviderPool.addProvider('remote', remoteBrowserProviderMock);
return testCafe.createBrowserConnection();
})
.then(bc => {
connection = bc;
connection.establish('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 ' +
'(KHTML, like Gecko) Chrome/41.0.2227.1 Safari/537.36');
});
});
after(async () => {
browserProviderPool.addProvider('remote', origRemoteBrowserProvider);
await connection.close();
return testCafe.close();
});
beforeEach(() => {
runner = testCafe.createRunner();
});
afterEach(() => {
consoleWrapper.messages.clear();
});
describe('.browsers()', () => {
it('Should raise an error if browser was not found for the alias', function () {
this.timeout(5000);
return runner
.browsers('browser42')
.reporter('list')
.src('test/server/data/test-suites/basic/testfile2.js')
.run()
.then(() => {
throw new Error('Promise rejection expected');
})
.catch((err) => {
expect(err.message).eql('Cannot find the browser. "browser42" is neither a ' +
'known browser alias, nor a path to an executable file.');
});
});
it('Should raise an error if an unprefixed path is provided', () => {
return runner
.browsers('/Applications/Firefox.app')
.reporter('list')
.src('test/server/data/test-suites/basic/testfile2.js')
.run()
.then(() => {
throw new Error('Promise rejection expected');
})
.catch(err => {
expect(err.message).eql('Cannot find the browser. "/Applications/Firefox.app" is neither a ' +
'known browser alias, nor a path to an executable file.');
});
});
it('Should raise an error if browser was not set', () => {
return runner
.reporter('list')
.src('test/server/data/test-suites/basic/testfile2.js')
.run()
.then(() => {
throw new Error('Promise rejection expected');
})
.catch(err => {
expect(err.message).eql('You have not specified a browser.');
});
});
it('Should raise an error for the multiple ".browsers" method call', () => {
try {
runner
.browsers('browser1')
.browsers('browser2');
throw new Error('Should raise an appropriate error.');
}
catch (err) {
expect(err.message).startsWith('You cannot call the "browsers" method more than once. Specify an array of parameters instead');
}
});
});
describe('.reporter()', () => {
it('Should raise an error if reporter was not found for the alias', () => {
return runner
.browsers(connection)
.reporter('reporter42')
.src('test/server/data/test-suites/basic/testfile2.js')
.run()
.then(() => {
throw new Error('Promise rejection expected');
})
.catch(err => {
expect(err.message).eql('The "reporter42" reporter does not exist. ' +
'Check the reporter parameter for errors.');
});
});
it('Should fallback to the default reporter if reporter was not set', () => {
const storedRunTaskFn = runner._runTask;
runner._runTask = ({ reporters }) => {
const reporterPlugin = reporters[0].plugin;
expect(reporterPlugin.name).eql('spec');
expect(reporterPlugin.reportFixtureStart).to.be.a('function');
expect(reporterPlugin.reportTestDone).to.be.a('function');
expect(reporterPlugin.reportTaskStart).to.be.a('function');
expect(reporterPlugin.reportTaskDone).to.be.a('function');
runner._runTask = storedRunTaskFn;
return Promise.resolve({});
};
return runner
.browsers(connection)
.src('test/server/data/test-suites/basic/testfile2.js')
.run();
});
it('Should raise an error if the reporter output has a wrong type', () => {
try {
runner.reporter('xunit', 9);
throw new Error('Should raise a valid error.');
}
catch (e) {
expect(e.message).eql("Specify a file name or a writable stream as the reporter's output target.");
}
});
it('Should raise an error for the multiple ".reporter" method call', () => {
try {
runner
.reporter('json')
.reporter('xunit');
throw new Error('Should raise an appropriate error.');
}
catch (err) {
expect(err.message).startsWith('You cannot call the "reporter" method more than once. Specify an array of parameters instead');
}
});
it('Should raise an error if null is specified as a reporter output stream (GH-3114)', () => {
try {
runner.reporter('json', null);
}
catch (e) {
expect(e.message).eql("Specify a file name or a writable stream as the reporter's output target.");
}
});
describe('Dashboard', () => {
const TEST_DASHBOARD_SETTINGS = {
token: 'test-token',
sendReport: true,
};
describe('Environment options', () => {
before(() => {
process.env.TESTCAFE_DASHBOARD_URL = 'test-url';
process.env.TESTCAFE_DASHBOARD_TOKEN = 'test-token';
process.env.TESTCAFE_DASHBOARD_BUILD_ID = 'test-id';
process.env.TESTCAFE_DASHBOARD_ENABLE_LOG = 'false';
process.env.TESTCAFE_DASHBOARD_NO_SCREENSHOT_UPLOAD = '0';
process.env.TESTCAFE_DASHBOARD_NO_VIDEO_UPLOAD = '1';
process.env.TESTCAFE_DASHBOARD_RESPONSE_TIMEOUT = '1000';
process.env.TESTCAFE_DASHBOARD_REQUEST_RETRY_COUNT = '5';
});
after(() => {
delete process.env.TESTCAFE_DASHBOARD_URL;
delete process.env.TESTCAFE_DASHBOARD_TOKEN;
delete process.env.TESTCAFE_DASHBOARD_BUILD_ID;
delete process.env.TESTCAFE_DASHBOARD_ENABLE_LOG;
delete process.env.TESTCAFE_DASHBOARD_NO_SCREENSHOT_UPLOAD;
delete process.env.TESTCAFE_DASHBOARD_NO_VIDEO_UPLOAD;
delete process.env.TESTCAFE_DASHBOARD_RESPONSE_TIMEOUT;
delete process.env.TESTCAFE_DASHBOARD_REQUEST_RETRY_COUNT;
});
it('Should add dashboard reporter options from environment', async () => {
await runner._addDashboardReporterIfNeeded();
const reporter = runner.configuration.getOption('reporter')[0];
expect(reporter.name).to.equal('dashboard');
expect(reporter.options).to.contains({
token: 'test-token',
sendReport: true,
url: 'test-url',
buildId: 'test-id',
noVideoUpload: true,
responseTimeout: 1000,
requestRetryCount: 5,
});
});
it('Should recover config options', async () => {
process.env.TESTCAFE_DASHBOARD_TOKEN = 'test-token';
runner.configuration.mergeOptions({ dashboard: { token: 'config-token ' } });
await runner._addDashboardReporterIfNeeded();
const reporter = runner.configuration.getOption('reporter')[0];
expect(reporter.name).to.equal('dashboard');
expect(reporter.options).to.contains({
token: 'test-token',
});
});
});
it('Should turn on screenshots flags autoTakeOnFails and takeOnFails', async () => {
runner._loadDashboardOptionsFromStorage = () => {
return TEST_DASHBOARD_SETTINGS;
};
await runner._addDashboardReporterIfNeeded();
await runner._turnOnScreenshotsIfNeeded();
expect(runner.configuration.getOption('screenshots').autoTakeOnFails).to.equal(true);
expect(runner.configuration.getOption('screenshots').takeOnFails).to.equal(true);
});
});
});
describe('.screenshots()', () => {
it('Should throw an error when the screenshots base path contains forbidden characters', () => {
return runner
.browsers(connection)
.screenshots('path:with*forbidden|chars')
.src('test/server/data/test-suites/basic/testfile2.js')
.run()
.then(() => {
throw new Error('Promise rejection expected');
})
.catch(err => {
expect(err.message).eql('There are forbidden characters in the "path:with*forbidden|chars" ' +
'screenshots base directory path:\n ' +
'\t":" at index 4\n\t"*" at index 9\n\t"|" at index 19\n');
});
});
it('Should throw an error when the screenshots pattern contains forbidden characters', () => {
return runner
.browsers(connection)
.screenshots('correct_path', false, '${TEST}:${BROWSER}')
.src('test/server/data/test-suites/basic/testfile2.js')
.run()
.then(() => {
throw new Error('Promise rejection expected');
})
.catch(err => {
expect(err.message).eql('There are forbidden characters in the "${TEST}:${BROWSER}" ' +
'screenshots path pattern:\n \t":" at index 7\n');
});
});
it('Should allow to use relative paths in the screenshots base path and path patterns', () => {
const storedRunTaskFn = runner._runTask;
runner._runTask = function () {
runner._runTask = storedRunTaskFn;
return Promise.resolve({});
};
return runner
.browsers(connection)
.screenshots('..', false, '${BROWSER}/./${TEST}')
.src('test/server/data/test-suites/basic/testfile2.js')
.run();
});
it('Should allow to specify path pattern without a base screenshot path', () => {
runner._createRunnableConfiguration = () => {
throw new Error('stop executing runner.');
};
return runner
.browsers(connection)
.screenshots(void 0, true, '${DATE}')
.src('test/server/data/test-suites/basic/testfile2.js')
.run()
.then(() => {
throw new Error('Promise rejection expected');
})
.catch(err => {
expect(err.message).eql('stop executing runner.');
expect(runner.configuration.getOption('screenshots').path).eql(path.resolve(process.cwd(), 'screenshots'));
expect(runner.configuration.getOption('screenshots').pathPattern).eql('${DATE}');
});
});
it('Should not display a message about "overridden options" after call "screenshots" method with undefined arguments', () => {
const savedConsoleLog = console.log;
console.log = consoleWrapper.log;
return runner
.screenshots(void 0, void 0, void 0)
.run({ skipJsErrors: true })
.catch(() => {
console.log = savedConsoleLog;
expect(consoleWrapper.messages.log).eql(null);
});
});
it('should allow to set object as a `screenshots` method parameter', async () => {
await runner
.screenshots({
path: 'path',
takeOnFails: true,
pathPattern: 'pathPattern',
fullPage: true,
});
await runner._setConfigurationOptions();
await runner._setBootstrapperOptions();
expect(runner.configuration.getOption('screenshots').path).eql('path');
expect(runner.configuration.getOption('screenshots').takeOnFails).eql(true);
expect(runner.configuration.getOption('screenshots').pathPattern).eql('pathPattern');
expect(runner.configuration.getOption('screenshots').fullPage).eql(true);
});
it('Validate screenshot options. The `screenshots` option has priority', () => {
runner.configuration.mergeOptions({
'screenshots': {
'path': 'path1',
'pathPattern': 'pattern1',
'fullPage': true,
},
'screenshotPath': 'path2',
'screenshotPathPattern': 'pattern2',
});
expect(runner._getScreenshotOptions()).eql({
path: 'path1',
pathPattern: 'pattern1',
takeOnFails: false,
});
});
it('Validate screenshot options. Obsolete options are still validated', () => {
runner.configuration.mergeOptions({
'screenshots': {
'fullPage': true,
},
'screenshotPath': 'path2',
'screenshotPathPattern': 'pattern2',
});
expect(runner._getScreenshotOptions()).eql({
path: 'path2',
pathPattern: 'pattern2',
takeOnFails: false,
});
});
it('Should use default `screenshots.path` if is not set', () => {
runner._createRunnableConfiguration = () => {
throw new Error('stop executing runner.');
};
return runner
.browsers(connection)
.src('test/server/data/test-suites/basic/testfile1.js')
.run()
.catch(err => {
expect(err.message).eql('stop executing runner.');
expect(runner.configuration.getOption('screenshots').path).eql(path.resolve(process.cwd(), 'screenshots'));
});
});
});
describe('--retry-test-pages', () => {
it('hostname is not localhost and ssl is disabled', () => {
runner.configuration.mergeOptions({ [OptionNames.retryTestPages]: true });
runner.configuration.mergeOptions({ [OptionNames.hostname]: 'http://example.com' });
return runner
.browsers(connection)
.src('test/server/data/test-suites/basic/testfile2.js')
.run()
.then(() => {
throw new Error('Promise rejection expected');
})
.catch(err => {
expect(err.message).eql(
'Cannot enable the \'retryTestPages\' option. Apply one of the following two solutions:\n' +
'-- set \'localhost\' as the value of the \'hostname\' option\n' +
'-- run TestCafe over HTTPS\n'
);
});
});
it('hostname is localhost and ssl is disabled', () => {
runner.configuration.mergeOptions({ [OptionNames.retryTestPages]: true });
runner._runTask = () => {
throw new Error('Promise rejection expected');
};
return runner
.browsers(connection)
.src('test/server/data/test-suites/basic/testfile2.js')
.run()
.catch(err => {
expect(err.message).eql('Promise rejection expected');
});
});
it('hostname is not localhost and ssl is enabled', () => {
runner.configuration.mergeOptions({ [OptionNames.retryTestPages]: true });
runner.configuration.mergeOptions({ [OptionNames.hostname]: 'http://example.com' });
runner.configuration.mergeOptions({ [OptionNames.ssl]: 'ssl' });
runner._runTask = () => {
throw new Error('Promise rejection expected');
};
return runner
.browsers(connection)
.src('test/server/data/test-suites/basic/testfile2.js')
.run()
.catch(err => {
expect(err.message).eql('Promise rejection expected');
});
});
});
describe('.video()', () => {
it('Should throw an error if video options are specified without a base video path', () => {
return runner
.browsers(connection)
.video(void 0, { failedOnly: true })
.src('test/server/data/test-suites/basic/testfile2.js')
.run()
.then(() => {
throw new Error('Promise rejection expected');
})
.catch(err => {
expect(err.message).eql('You cannot manage advanced video parameters when the video recording capability is off. ' +
'Specify the root storage folder for video content to enable video recording.');
});
});
it('Should throw an error if video encoding options are specified without a base video path', () => {
return runner
.browsers(connection)
.video(void 0, null, { 'c:v': 'x264' })
.src('test/server/data/test-suites/basic/testfile2.js')
.run()
.then(() => {
throw new Error('Promise rejection expected');
})
.catch(err => {
expect(err.message).eql('You cannot manage advanced video parameters when the video recording capability is off. ' +
'Specify the root storage folder for video content to enable video recording.');
});
});
});
describe('.src()', () => {
it('Should accept source files in different forms', () => {
const cwd = process.cwd();
const storedRunTaskFn = runner._runTask;
const storedGetBrowserConnectionsFn = runner.bootstrapper._getBrowserConnections;
const expectedFiles = [
'test/server/data/test-suites/basic/testfile1.js',
'test/server/data/test-suites/basic/testfile2.js',
'test/server/data/test-suites/basic/testfile3.js',
].map(file => path.resolve(cwd, file));
runner.bootstrapper._getBrowserConnections = () => {
runner.bootstrapper._getBrowserConnections = storedGetBrowserConnectionsFn;
return Promise.resolve({
browserConnectionGroups: [],
});
};
runner._runTask = ({ tests }) => {
const actualFiles = uniqBy(tests.map(test => test.testFile.filename));
expect(actualFiles).eql(expectedFiles);
runner._runTask = storedRunTaskFn;
return Promise.resolve({});
};
return runner
.browsers(BROWSER_NAME)
.src('test/server/data/test-suites/basic/testfile1.js',
[
'test/server/data/test-suites/basic/*.js',
'test/server/data/test-suites/basic',
]
)
.run();
});
it('Should use default `src` if the source was not set', () => {
runner._createRunnableConfiguration = () => {
throw new Error('stop executing runner.');
};
return runner
.browsers(connection)
.reporter('list')
.run()
.catch(err => {
expect(err.message).eql('stop executing runner.');
expect(runner.configuration.getOption('src')).eql(['tests', 'test']);
});
});
it('Should raise an error if the source and imported module have no tests', () => {
return runner
.browsers(connection)
.src(['test/server/data/test-suites/test-as-module/without-tests/testfile.js'])
.run()
.catch(err => {
expect(err.message).eql("Source files do not contain valid 'fixture' and 'test' declarations.");
});
});
it('Should raise an error for the multiple ".src" method call', () => {
try {
runner
.src('/source1')
.src('/source2');
throw new Error('Should raise an appropriate error.');
}
catch (err) {
expect(err.message).startsWith('You cannot call the "src" method more than once. Specify an array of parameters instead');
}
});
});
describe('.filter()', () => {
beforeEach(() => {
runner
.browsers(connection)
.reporter('list')
.src([
'test/server/data/test-suites/basic/testfile1.js',
'test/server/data/test-suites/basic/testfile2.js',
'test/server/data/test-suites/filter/meta.js',
]);
});
function testFilter (filterFn, expectedTestNames) {
const storedRunTaskFn = runner._runTask;
runner.filter(filterFn);
runner._runTask = ({ tests }) => {
const actualTestNames = tests.map(test =>test.name).sort();
expectedTestNames = expectedTestNames.sort();
expect(actualTestNames).eql(expectedTestNames);
runner._runTask = storedRunTaskFn;
return Promise.resolve({});
};
return runner.run();
}
it('Should filter by test name', () => {
const filter = testName => !testName.includes('Fixture2');
const expectedTestNames = [
'Fixture1Test1',
'Fixture1Test2',
'Fixture3Test1',
'Fixture4Test1',
'Fixture5Test1',
'Fixture5Test2',
];
return testFilter(filter, expectedTestNames);
});
it('Should filter by fixture name', () => {
const filter = (testName, fixtureName) => fixtureName === 'Fixture1';
const expectedTestNames = [
'Fixture1Test1',
'Fixture1Test2',
];
return testFilter(filter, expectedTestNames);
});
it('Should filter by fixture path', () => {
const filter = (testName, fixtureName, fixturePath) => fixturePath.includes('testfile2.js');
const expectedTestNames = ['Fixture3Test1'];
return testFilter(filter, expectedTestNames);
});
it('Should filter by test meta', () => {
const filter = (testName, fixtureName, fixturePath, testMeta) => testMeta.meta === 'test';
const expectedTestNames = ['Fixture5Test2'];
return testFilter(filter, expectedTestNames);
});
it('Should filter by fixture meta', () => {
const filter = (testName, fixtureName, fixturePath, testMeta, fixtureMeta) => fixtureMeta.meta === 'test';
const expectedTestNames = ['Fixture4Test1'];
return testFilter(filter, expectedTestNames);
});
it('Should filter by async predicate', () => {
const filter = async testName => {
await new Promise(r => setTimeout(r, 2000));
return testName.includes('Fixture5');
};
const expectedTestNames = [
'Fixture5Test1',
'Fixture5Test2',
];
return testFilter(filter, expectedTestNames);
});
it('Should raise an error if all tests are rejected by the filter', () => {
return runner
.filter(() => false)
.run()
.then(() => {
throw new Error('Promise rejection expected');
})
.catch(err => {
expect(err.message).eql('No tests match your filter.\n' +
'See https://testcafe.io/documentation/402638/reference/configuration-file#filter.');
});
});
});
describe('.run()', () => {
it('Should not create a new remote browser connection if tests are not found', () => {
const origGenerateId = BrowserConnection._generateId;
let connectionsCount = 0;
BrowserConnection._generateId = () => {
connectionsCount++;
return origGenerateId();
};
return runner
.browsers(connection)
.reporter('list')
.src(['non-existing-file-1.js', 'non-existing-file-2.js'])
.run()
.then(() => {
BrowserConnection._generateId = origGenerateId;
throw new Error('Promise rejection expected');
})
.catch(err => {
BrowserConnection._generateId = origGenerateId;
expect(err.message).eql(
`Could not find test files at the following location: "${process.cwd()}".\n` +
'Check patterns for errors:\n' +
'\n' +
'non-existing-file-1.js\n' +
'non-existing-file-2.js\n' +
'\n' +
'or launch TestCafe from a different directory.\n' +
'For more information on how to specify test locations, see https://testcafe.io/documentation/402639/reference/command-line-interface#file-pathglob-pattern.');
expect(connectionsCount).eql(0);
});
});
it('Should raise an error if the browser connections are not opened', function () {
return testCafe
.createBrowserConnection()
.then(brokenConnection => {
return runner
.browsers(brokenConnection)
.reporter('list')
.src('test/server/data/test-suites/basic/testfile2.js')
.run({ browserInitTimeout: 100 });
})
.then(() => {
throw new Error('Promise rejection expected');
})
.catch(err => {
expect(err.message).eql('Cannot establish one or more browser connections.\n' +
'1 of 1 browser connections have not been established:\n' +
'- remote\n\n' +
'Hints:\n' +
'- Increase the value of the "browserInitTimeout" option if it is too low ' +
'(currently: 0.1 seconds for all browsers). This option determines how long TestCafe waits for browsers to be ready.\n' +
'- The error can also be caused by network issues or remote device failure. ' +
'Make sure that your network connection is stable and you can reach the remote device.');
});
});
it('Should raise an error if browser gets disconnected before bootstrapping', done => {
testCafe
.createBrowserConnection()
.then(brokenConnection => {
brokenConnection.establish('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 ' +
'(KHTML, like Gecko) Chrome/41.0.2227.1 Safari/537.36');
brokenConnection.on('error', () => {
runner
.run()
.then(() => {
throw new Error('Promise rejection expected');
})
.catch(err => {
expect(err.message).eql('The following browsers disconnected: ' +
'Chrome 41.0.2227.1 / macOS 10.10.1. Cannot run further tests.');
})
.then(done)
.catch(done);
});
runner.browsers(brokenConnection)
.reporter('list')
.src('test/server/data/test-suites/basic/testfile2.js');
brokenConnection.emit('error', new Error('It happened'));
});
});
it('Should raise an error if browser disconnected during bootstrapping', () => {
return Promise
.all(times(2, () => testCafe.createBrowserConnection()))
.then(connections => {
const run = runner
.browsers(connections[0], connections[1])
.reporter('list')
.src('test/server/data/test-suites/basic/testfile2.js')
.run();
connections[0].HEARTBEAT_TIMEOUT = 200;
connections[1].HEARTBEAT_TIMEOUT = 200;
const options = {
url: connections[0].url,
followRedirect: false,
headers: {
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 ' +
'(KHTML, like Gecko) Chrome/41.0.2227.1 Safari/537.36',
},
};
request(options);
return run;
})
.then(() => {
throw new Error('Promise rejection expected');
})
.catch(err => {
expect(err.message).eql('The Chrome 41.0.2227.1 / macOS 10.10.1 browser disconnected. ' +
'If you did not close the browser yourself, browser performance or network issues may be at fault.');
});
});
it('Should raise an error if connection breaks while tests are running', function () {
const test = this.test;
return testCafe
.createBrowserConnection()
.then(brokenConnection => {
brokenConnection.establish('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 ' +
'(KHTML, like Gecko) Chrome/41.0.2227.1 Safari/537.36');
const run = runner
.browsers(brokenConnection)
.reporter('json')
.src('test/server/data/test-suites/basic/testfile2.js')
.run();
function check () {
setTimeout(() => {
brokenConnection.getStatus().then(status => {
if (test.timedOut || status.cmd === COMMAND.run)
brokenConnection.emit('error', new Error('I have failed :('));
else
check();
}).catch(err => {
throw err;
});
}, 200);
}
check();
return run;
})
.then(() => {
throw new Error('Promise rejection expected');
})
.catch(err => {
expect(err.message).eql('I have failed :(');
});
});
it('Should raise an error if speed option has wrong value', function () {
let exceptionCount = 0;
const incorrectSpeedError = speed => {
return runner
.run({ speed })
.catch(err => {
exceptionCount++;
expect(err.message).eql('Speed should be a number between 0.01 and 1.');
});
};
return Promise.resolve()
.then(() => incorrectSpeedError('yo'))
.then(() => incorrectSpeedError(-0.01))
.then(() => incorrectSpeedError(0))
.then(() => incorrectSpeedError(1.01))
.then(() => expect(exceptionCount).to.be.eql(4));
});
it('Should raise an error if concurrency option has wrong value', () => {
let exceptionCount = 0;
const incorrectConcurrencyFactorError = concurrency => {
return runner
.concurrency(concurrency)
.run()
.catch(err => {
exceptionCount++;
expect(err.message).eql('The concurrency factor should be an integer greater than or equal to 1.');
});
};
return Promise.resolve()
.then(() => incorrectConcurrencyFactorError('yo'))
.then(() => incorrectConcurrencyFactorError(-1))
.then(() => incorrectConcurrencyFactorError(0.1))
.then(() => incorrectConcurrencyFactorError(0))
.then(() => expect(exceptionCount).to.be.eql(4));
});
it('Should raise an error if proxyBypass option has wrong type', () => {
let exceptionCount = 0;
const expectProxyBypassError = (proxyBypass, type) => {
runner.configuration.mergeOptions({ proxyBypass });
return runner
.run()
.catch(err => {
exceptionCount++;
expect(err.message).contains(`The "proxyBypass" argument (${type}) is not of expected type (string or an array)`);
});
};
return expectProxyBypassError(1, 'number')
.then(() => expectProxyBypassError({}, 'object'))
.then(() => expectProxyBypassError(true, 'boolean'))
.then(() => {
expect(exceptionCount).to.be.eql(3);
delete runner.configuration._options.proxyBypass;
});
});
it('Should not display a message about "overridden options" after call "run" method with flags with undefined value', () => {
const savedConsoleLog = console.log;
console.log = consoleWrapper.log;
return runner
.run()
.catch(() => {
console.log = savedConsoleLog;
expect(consoleWrapper.messages.log).eql(null);
});
});
it('Should use the default debugLogger if necessary', () => {
const defaultLogger = require('../../lib/notifications/debug-logger');
runner._validateDebugLogger();
expect(runner.configuration.getOption('debugLogger')).to.deep.equal(defaultLogger);
runner.configuration.mergeOptions({ debugLogger: null });
runner._validateDebugLogger();
expect(runner.configuration.getOption('debugLogger')).to.be.null;
const customLogger = {
showBreakpoint: 'foo',
hideBreakpoint: () => {},
};
runner.configuration.mergeOptions({ debugLogger: customLogger });
runner._validateDebugLogger();
expect(runner.configuration.getOption('debugLogger')).to.deep.equal(defaultLogger);
customLogger.showBreakpoint = () => {};
runner.configuration.mergeOptions({ debugLogger: customLogger });
runner._validateDebugLogger();
expect(runner.configuration.getOption('debugLogger')).to.deep.equal(customLogger);
});