/
net_stubbing.cy.ts
4033 lines (3397 loc) · 121 KB
/
net_stubbing.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
import { getDisplayUrlMatcher } from '@packages/driver/src/cy/net-stubbing/route-matcher-log'
import type { RouteMatcherOptions } from '@packages/net-stubbing/lib/external-types'
const testFail = (cb, expectedDocsUrl = 'https://on.cypress.io/intercept') => {
cy.on('fail', (err) => {
// @ts-ignore
const docsUrl = Array.isArray(err.docsUrl) ? err.docsUrl[0] : err.docsUrl
expect(docsUrl).to.eq(expectedDocsUrl)
cb(err)
})
}
// Due to an issue with requests leaking between tests, we need to ensure that routes are unique from test to test
// See https://github.com/cypress-io/cypress/issues/20397
let routeCount = 0
const uniqueRoute = (route) => {
routeCount += 1
return `${route}-${routeCount}`
}
// TODO: fix flaky tests https://github.com/cypress-io/cypress/issues/23434
describe('network stubbing', { retries: 15 }, function () {
const { $, _, sinon, state, Promise } = Cypress
beforeEach(function () {
cy.spy(Cypress.utils, 'warning')
})
context('cy.intercept()', function () {
context('emits as expected', function () {
beforeEach(function () {
// we don't use cy.spy() because it causes an infinite loop with logging events
this.sandbox = sinon.createSandbox()
this.emit = this.sandbox.spy(Cypress, 'emit').withArgs('backend:request', 'net', 'route:added')
this.testRoute = function (options, handler, expectedEvent, expectedRoute) {
cy.intercept(options, handler).then(function () {
const routeId = _.findKey(state('routes'), { handler })
const route = state('routes')[routeId!]
expectedEvent.routeId = routeId
expect(this.emit).to.be.calledWith('backend:request', 'net', 'route:added', expectedEvent)
expect(route.handler).to.deep.eq(expectedRoute.handler)
expect(route.options).to.deep.eq(expectedRoute.options)
})
}
})
afterEach(function () {
this.sandbox.restore()
})
it('url, body and stores Route', function () {
const handler = 'bar'
const url = uniqueRoute('http://foo.invalid')
const expectedEvent = {
routeMatcher: {
url: {
type: 'glob',
value: url,
},
},
staticResponse: {
body: 'bar',
},
hasInterceptor: false,
}
const expectedRoute = {
options: { url },
handler,
}
this.testRoute(url, handler, expectedEvent, expectedRoute)
})
it('url, HTTPController and stores Route', function () {
const handler = () => {
return {}
}
const url = uniqueRoute('http://foo.invalid')
const expectedEvent = {
routeMatcher: {
url: {
type: 'glob',
value: url,
},
},
hasInterceptor: true,
}
const expectedRoute = {
options: { url },
handler,
}
this.testRoute(url, handler, expectedEvent, expectedRoute)
})
it('regex values stringified and other values copied and stores Route', function () {
const handler = () => {
return {}
}
const options = {
auth: {
username: 'foo',
password: /.*/,
},
headers: {
'Accept-Language': /hylian/i,
'Content-Encoding': 'corrupted',
},
hostname: /any.com/,
https: true,
method: 'POST',
path: '/bing?foo',
pathname: '/bazz',
port: [1, 2, 3, 4, 5, 6],
query: {
bar: 'baz',
quuz: /(.*)quux/gi,
},
url: uniqueRoute('http://foo.invalid'),
}
const expectedEvent = {
routeMatcher: {
auth: {
username: {
type: 'glob',
value: options.auth.username,
},
password: {
type: 'regex',
value: '/.*/',
},
},
headers: {
'accept-language': {
type: 'regex',
value: '/hylian/i',
},
'content-encoding': {
type: 'glob',
value: options.headers['Content-Encoding'],
},
},
hostname: {
type: 'regex',
value: '/any.com/',
},
https: options.https,
method: {
type: 'glob',
value: options.method,
},
path: {
type: 'glob',
value: options.path,
},
pathname: {
type: 'glob',
value: options.pathname,
},
port: options.port,
query: {
bar: {
type: 'glob',
value: options.query.bar,
},
quuz: {
type: 'regex',
value: '/(.*)quux/gi',
},
},
url: {
type: 'glob',
value: options.url,
},
},
hasInterceptor: true,
}
const expectedRoute = {
options,
handler,
}
this.testRoute(options, handler, expectedEvent, expectedRoute)
})
it('mergeRouteMatcher + string url works', function () {
const url = uniqueRoute('/foo')
const handler = (req) => {
// @ts-ignore
const routeId = _.findKey(state('routes'), { handler })
const route = state('routes')[routeId!]
// @ts-ignore
expectedEvent.routeId = routeId
expect(this.emit).to.be.calledWith('backend:request', 'net', 'route:added', expectedEvent)
expect(route.handler).to.deep.eq(expectedRoute.handler)
expect(route.options).to.deep.eq(expectedRoute.options)
req.reply('a')
}
const expectedRoute = {
options: { url: `${url}*`, middleware: true },
handler,
}
const expectedEvent = {
routeMatcher: {
url: {
type: 'glob',
value: `${url}*`,
},
middleware: true,
},
hasInterceptor: true,
}
cy.intercept(`${url}*`, { middleware: true }, handler).as('get')
.then(() => {
return $.get(url)
})
.wait('@get')
})
// @see https://github.com/cypress-io/cypress/pull/16390
it('mergeRouteMatcher + regex url works', function () {
const url = uniqueRoute('/foo')
const regexUrl = new RegExp(`^${url}.*`)
const handler = (req) => {
// @ts-ignore
const routeId = _.findKey(state('routes'), { handler })
const route = state('routes')[routeId!]
// @ts-ignore
expectedEvent.routeId = routeId
expect(this.emit).to.be.calledWith('backend:request', 'net', 'route:added', expectedEvent)
expect(route.handler).to.deep.eq(expectedRoute.handler)
expect(route.options).to.deep.eq(expectedRoute.options)
req.reply('a')
}
const expectedRoute = {
options: { url: regexUrl, middleware: true },
handler,
}
const expectedEvent = {
routeMatcher: {
url: {
type: 'regex',
value: String(regexUrl),
},
middleware: true,
},
hasInterceptor: true,
}
cy.intercept(regexUrl, { middleware: true }, handler).as('get')
.then(() => {
return $.get(url)
})
.wait('@get')
})
})
// https://github.com/cypress-io/cypress/issues/8729
it('resolve ambiguity between overloaded definitions', () => {
cy.intercept('POST', '/post-only').as('create')
cy.window().then((win) => {
win.eval(
`fetch("/post-only", {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
});`,
)
})
cy.wait('@create')
})
// https://github.com/cypress-io/cypress/issues/9313
it('lower-cased method works', () => {
cy.intercept({
method: 'post',
url: '/post-only',
}).as('create')
cy.window().then((win) => {
win.eval(
`fetch("/post-only", {
method: 'post', // *GET, POST, PUT, DELETE, etc.
});`,
)
})
cy.wait('@create')
})
// @see https://github.com/cypress-io/cypress/issues/16117
it('can statically stub a url response with headers', () => {
cy.intercept('/url', { headers: { foo: 'bar' }, body: 'something' })
})
// TODO: implement warning in cy.intercept if appropriate
// https://github.com/cypress-io/cypress/issues/2372
it.skip('warns if a percent-encoded URL is used', function () {
cy.intercept('GET', '/foo%25bar').then(function () {
expect(Cypress.utils.warning).to.be.calledWith('A URL with percent-encoded characters was passed to cy.intercept(), but cy.intercept() expects a decoded URL.\n\nDid you mean to pass "/foo%bar"?')
})
})
// NOTE: see todo on 'warns if a percent-encoded URL is used'
it.skip('does not warn if an invalid percent-encoded URL is used', function () {
cy.intercept('GET', 'http://example.com/%E0%A4%A').then(function () {
expect(Cypress.utils.warning).to.not.be.called
})
})
context('overrides', function () {
it('chains middleware with string matcher as expected', function () {
const e: string[] = []
cy
.intercept('/dump-headers*', { middleware: true }, (req) => {
e.push('mware req handler')
req.on('before:response', (res) => {
e.push('mware before:response')
})
req.on('response', (res) => {
e.push('mware response')
})
req.on('after:response', (res) => {
e.push('mware after:response')
})
})
.intercept('/dump-headers*', (req) => {
e.push('normal req handler')
req.reply(() => {
e.push('normal res handler')
})
})
.then(() => {
return $.get('/dump-headers')
})
.wrap(e).should('have.all.members', [
'mware req handler',
'normal req handler',
'mware before:response',
'normal res handler',
'mware response',
'mware after:response',
])
})
it('chains request handlers from bottom-up', function (done) {
cy.intercept('/dump-headers*', (req) => {
req.reply((res) => {
expect(res.body).to.include('"x-foo":"bar"')
done()
})
})
.intercept('/dump-headers*', (req) => req.headers['x-foo'] = 'bar')
.then(() => {
$.get('/dump-headers')
})
})
/**
* https://github.com/cypress-io/cypress/issues/9302
* https://github.com/cypress-io/cypress/discussions/9339
* https://github.com/cypress-io/cypress/issues/4460
*/
it('can override a StaticResponse with another StaticResponse', function () {
const url = uniqueRoute('/items')
cy.intercept('GET', `${url}*`, [])
.intercept('GET', `${url}*`, ['foo', 'bar'])
.then(() => {
return $.getJSON(url)
})
.should('deep.eq', ['foo', 'bar'])
})
/**
* https://github.com/cypress-io/cypress/discussions/9587
*/
it('can override an interceptor with another interceptor', function () {
cy.intercept('GET', '**/mydata?**', (req) => {
throw new Error('this should not be called')
})
.intercept('GET', '/mydata*', (req) => {
req.reply({ body: [1, 2, 3, 4, 5] })
}).as('mydata')
.then(() => {
return $.getJSON('/mydata?abc')
})
.should('deep.eq', [1, 2, 3, 4, 5])
.wait('@mydata')
})
it('sends a StaticResponse if the newest stub is a StaticResponse', function () {
const url = uniqueRoute('/foo')
cy.intercept(`${url}*`, () => {
throw new Error('this should not be called')
}).as('interceptor')
.intercept(`${url}*`, { body: 'something' }).as('staticresponse')
.intercept(`${url}*`).as('spy')
.then(() => {
return $.get(url)
})
.should('deep.eq', 'something')
.wait('@spy')
.wait('@staticresponse')
.get('@interceptor.all').should('have.length', 0)
})
it('sends a StaticResponse if a request handler does not supply a response', function () {
const url = uniqueRoute('/foo')
cy.intercept(`${url}*`, { body: 'something' }).as('staticresponse')
.intercept(`${url}*`, () => { }).as('interceptor')
.then(() => {
return $.get(url)
})
.should('deep.eq', 'something')
.wait('@interceptor')
.wait('@staticresponse')
})
context('request handler chaining', function () {
it('passes request through in reverse order', function () {
cy.intercept('/dump-method', function (req) {
expect(req.method).to.eq('PATCH')
req.reply()
}).intercept('/dump-method', function (req) {
expect(req.method).to.eq('POST')
req.method = 'PATCH'
}).intercept('/dump-method', function (req) {
expect(req.method).to.eq('GET')
req.method = 'POST'
}).visit('/dump-method').contains('PATCH')
})
it('stops passing request through once req.reply called', function () {
cy.intercept('/dump-method', function (req) {
throw new Error('this should not have been reached')
}).intercept('/dump-method', function (req) {
req.reply()
}).visit('/dump-method').contains('GET')
})
})
context('response handler chaining', function () {
it('passes response through in reverse order', function () {
cy.intercept('/dump-method', function (req) {
req.on('before:response', (res) => {
expect(res.body).to.contain('new body')
})
}).intercept('/dump-method', function (req) {
req.on('before:response', (res) => {
expect(res.body).to.contain('GET')
res.body = 'new body'
})
}).visit('/dump-method')
.contains('new body')
})
it('stops passing response through once res.send called', function () {
cy.intercept('/dump-method', function (req) {
req.on('before:response', (res) => {
throw new Error('this should not have been reached')
})
}).intercept('/dump-method', function (req) {
req.on('before:response', (res) => {
res.send()
})
}).visit('/dump-method').contains('GET')
})
})
// https://github.com/cypress-io/cypress/issues/16292
describe('multibyte utf8', () => {
const multibyteUtf8 = [
// 1. When there's problem in the chunkEnd
// * 2 bytes
'12345678901234567890123Ф',
// * 3 bytes
'12345678901234567890123안',
'1234567890123456789012안',
// * 4 bytes
'12345678901234567890123😀',
'1234567890123456789012😀',
'123456789012345678901😀',
// 2. When there's a problem in the chunkBegin
// * 2 bytes
'dummyФ12345678901234567890123',
// * 3 bytes
'dummy안12345678901234567890123',
'dummy안1234567890123456789012',
// * 4 bytes
'dummy😀12345678901234567890123',
'dummy😀1234567890123456789012',
'dummy😀123456789012345678901',
]
multibyteUtf8.forEach((str) => {
it(str, () => {
cy.intercept('https://example.com/test', {
body: { result: 'ok' },
}).as('testRequest')
cy.window().then(() => {
let xhr = new XMLHttpRequest()
xhr.open('POST', 'https://example.com/test')
xhr.setRequestHeader('Content-Type', 'application/json')
xhr.send(str)
})
cy.wait('@testRequest')
.its('request')
.then((req) => {
expect(req.body).to.eq(str)
})
})
})
})
})
context('logging', function () {
beforeEach(function () {
this.logs = []
cy.on('log:added', (attrs, log) => {
if (attrs.instrument === 'route') {
this.lastLog = log
this.logs.push(log)
}
})
})
it('has name of route', function () {
const url = uniqueRoute('/foo')
cy.intercept(url, {}).then(function () {
expect(this.lastLog.get('name')).to.eq('route')
})
})
it('uses the wildcard URL', function () {
cy.intercept('*', {}).then(function () {
expect(this.lastLog.get('url')).to.eq('*')
})
})
// @see https://github.com/cypress-io/cypress/issues/9403
// see getDisplayUrlMatcher unit tests for more test cases
it('stringifies complex matchers', function () {
cy.intercept({ hostname: 'foo.net', port: 1234 }).then(function () {
expect(this.lastLog.get('url')).to.eq('{hostname: foo.net, port: 1234}')
expect(this.lastLog.get('method')).to.eq('*')
})
})
describe('numResponses', function () {
it('is initially 0', function () {
cy.intercept(/foo/, {}).then(() => {
let lastLog
lastLog = this.lastLog
expect(lastLog.get('numResponses')).to.eq(0)
})
})
it('is incremented to 2', function () {
const url = uniqueRoute('/foo')
const regexUrl = new RegExp(url)
cy.intercept(regexUrl, {}).then(function () {
$.get(url)
}).wrap(this).invoke('lastLog.get', 'numResponses').should('eq', 1)
})
it('is incremented for each matching request', function () {
const url = uniqueRoute('/foo')
const regexUrl = new RegExp(url)
cy.intercept(regexUrl, {}).then(function () {
return Promise.all([$.get(url), $.get(url), $.get(url)])
}).wrap(this).invoke('lastLog.get', 'numResponses').should('eq', 3)
})
})
})
context('errors', function () {
beforeEach(function () {
this.logs = []
cy.on('log:added', (attrs, log) => {
// @ts-ignore
if (log.get('name') !== 'intercept') {
return
}
this.lastLog = log
this.logs.push(log)
})
})
it('url must be a string or regexp', function (done) {
testFail((err) => {
expect(err.message).to.include('`url` must be a string or a regular expression')
done()
})
// @ts-ignore: should fail
cy.intercept({
// @ts-ignore
url: {},
})
})
// TODO: not currently implemented
it.skip('fails when method is invalid', function (done) {
const url = uniqueRoute('/foo')
testFail((err) => {
expect(err.message).to.include('cy.intercept() was called with an invalid method: \'POSTS\'.')
done()
})
cy.intercept('post', url, {})
})
it('requires a url when given a response', function (done) {
testFail((err) => {
expect(err.message).to.include('The RouteMatcher does not contain any keys. You must pass something to match on.')
done()
})
cy.intercept({})
})
it('requires arguments', function (done) {
testFail((err) => {
expect(err.message).to.include('An invalid RouteMatcher was supplied to `cy.intercept()`. The RouteMatcher does not contain any keys. You must pass something to match on.')
done()
})
// @ts-ignore - should fail
cy.intercept()
})
it('cannot merge url with url', function (done) {
const url = uniqueRoute('/bar')
testFail((err) => {
expect(err.message).to.include('When invoking \`cy.intercept()\` with a \`RouteMatcher\` as the second parameter, \`url\` can only be specified as the first parameter')
done()
})
// @ts-ignore - should fail
cy.intercept(url, { url }, () => {})
})
it('cannot pass RouteMatcherOptions in 2nd arg with no handler', function (done) {
const url = uniqueRoute('/foo')
testFail((err) => {
expect(err.message).to.include('When invoking \`cy.intercept()\` with a \`RouteMatcher\` as the second parameter, a handler (function or \`StaticResponse\`) must be specified as the third parameter.')
done()
})
// sadly this passes typecheck, but the runtime error will prevent this
cy.intercept(url, { middleware: true })
})
context('with an unexpected number of arguments', function () {
const url = uniqueRoute('/url')
it('cy.intercept(url, handler?)', function (done) {
testFail((err) => {
expect(err.message).to.include('The `cy.intercept(url, handler?)` signature accepts a maximum of 2 arguments, but 3 arguments were passed.')
done()
})
// @ts-ignore
cy.intercept(url, { forceNetworkError: true }, () => {})
})
it('cy.intercept(url, mergeRouteMatcher, handler)', function (done) {
const url = uniqueRoute('/url')
testFail((err) => {
expect(err.message).to.include('The `cy.intercept(url, mergeRouteMatcher, handler)` signature accepts a maximum of 3 arguments, but 4 arguments were passed.')
done()
})
// @ts-ignore
cy.intercept(url, { middleware: true }, { forceNetworkError: true }, () => {})
})
it('cy.intercept(method, url, handler?)', function (done) {
const url = uniqueRoute('/url')
testFail((err) => {
expect(err.message).to.include('The `cy.intercept(method, url, handler?)` signature accepts a maximum of 3 arguments, but 4 arguments were passed.')
done()
})
// @ts-ignore
cy.intercept('POST', url, { forceNetworkError: true }, () => {})
})
})
context('with invalid RouteMatcher', function () {
it('requires unique header names', function (done) {
testFail((err) => {
expect(err.message).to.include('`FOO` was specified more than once in `headers`. Header fields can only be matched once (HTTP header field names are case-insensitive).')
done()
})
cy.intercept({
headers: {
foo: 'bar',
FOO: 'bar',
},
})
})
it('requires StringMatcher header values', function (done) {
testFail((err) => {
expect(err.message).to.include('`headers.wrong` must be a string or a regular expression.')
done()
})
// @ts-ignore this is invalid on purpose
cy.intercept({
headers: {
good: 'string',
fine: /regexp/,
// @ts-ignore
wrong: 3,
},
})
})
it('errors on matchUrlAgainstPath usage', function (done) {
testFail((err) => {
expect(err.message).to.include('`matchUrlAgainstPath` was removed in Cypress 7.0.0')
done()
})
// @ts-ignore
cy.intercept({ matchUrlAgainstPath: true })
})
it('errors on unknown prop', function (done) {
testFail((err) => {
expect(err.message).to.include('An unknown \`RouteMatcher\` property was passed: `wrong`')
done()
})
// @ts-ignore
cy.intercept({ wrong: true })
})
it('times must be a positive integer', function (done) {
testFail((err) => {
expect(err.message).to.include('`times` must be a positive integer.')
done()
})
cy
.intercept({ times: 9.75 })
})
it('string hostname must be a valid domain name', function (done) {
testFail((err) => {
expect(err.message).to.include('`hostname` must be a valid host name or domain name.')
done()
})
cy.intercept({ hostname: 'http://website.web' })
})
// https://github.com/cypress-io/cypress/issues/17015
it('string hostname can be "localhost"', () => {
cy.intercept({ hostname: 'localhost' })
})
it('string hostname can be unicode', () => {
cy.intercept({ hostname: 'はじめよう.みんな' })
})
})
context('with invalid handler', function () {
[false, null].forEach(function (handler) {
const name = String(handler)
it(`${name} fails`, function (done) {
testFail((err) => {
expect(err).to.eq(this.lastLog.get('error'))
expect(err.message).to.contain(`You passed: ${name}`)
done()
})
// @ts-ignore - this should error
cy.intercept('/', handler)
})
})
})
context('with invalid StaticResponse', function () {
[
[
'forceNetworkError set but not alone',
{
forceNetworkError: true,
body: 'aaa',
},
'must be the only option',
],
[
'statusCode out of range',
{
statusCode: -1,
},
'must be a number',
],
].forEach(function ([name, handler, expectedErr]) {
it(`${name} fails`, function (done) {
testFail((err) => {
expect(err).to.eq(this.lastLog.get('error'))
expect(err.message).to.contain(expectedErr)
expect(err.message).to.contain(`You passed: ${JSON.stringify(handler, null, 2)}`)
done()
})
// @ts-ignore - this should error
cy.intercept('/', handler)
})
})
})
})
})
context('events', function () {
// @see https://github.com/cypress-io/cypress/issues/9170
it('gracefully handles request received without a known route', function () {
cy.intercept('/valid.json', (req) => {
req.reply({ bad: 'should not be received' })
})
.then(() => {
const routeIds = _.keys(state('routes'))
// delete the driver-side route - the server-side route will still exist and cause an event
// to be emitted to the driver
delete state('routes')[routeIds[0]]
expect(state('routes')).to.deep.eq({})
return $.get('/fixtures/valid.json')
})
.then((body) => {
expect(body).to.include({ foo: 1 })
})
})
it('gracefully handles response received without a known route', function () {
cy.intercept('/valid.json', (req) => {
state('routes', {})
req.reply((res) => {
res.send({ bad: 'should not be received' })
})
})
.then(() => {
return $.get('/fixtures/valid.json')
})
.then((body) => {
expect(body).to.include({ foo: 1 })
})
})
it('gracefully handles response completed without a known route', function () {
cy.intercept('/fixtures/valid.json*', (req) => {
req.reply((res) => {
state('routes', {})
res.send({ bar: 2 })
})
})
.then(() => {
return $.get('/fixtures/valid.json')
})
.then((body) => {
expect(body).to.include({ bar: 2 })
})
})
})
context('network handling', function () {
// @see https://github.com/cypress-io/cypress/issues/8497
it('can load transfer-encoding: chunked redirects', function () {
cy.intercept('*')
const url4 = 'http://localhost:3501/fixtures/generic.html'
const url3 = `http://localhost:3501/redirect?href=${encodeURIComponent(url4)}`
const url2 = `https://localhost:3502/redirect?chunked=1&href=${encodeURIComponent(url3)}`
const url1 = `https://localhost:3502/redirect?chunked=1&href=${encodeURIComponent(url2)}`
cy.visit(url1)
.location('href').should('eq', url4)
})
context('can intercept against any domain', function () {
beforeEach(function () {
// reset origin
cy.visit('http://localhost:3500/fixtures/generic.html')
})
it('different origin (HTTP)', function () {
const url = uniqueRoute('/foo')
cy.intercept(`${url}*`).as('foo')
.then(() => {
$.get(`http://baz.foobar.com:3501${url}`)
})
.wait('@foo')
})
it('different origin with response interception (HTTP)', function () {
cy.intercept('/fixtures/xhr.html*', (req) => {
req.reply((res) => {
expect(res.body).to.include('xhr fixture')
res.body = 'replaced the body'
})
}).as('foo')
.then(() => {
return $.get('http://baz.foobar.com:3501/fixtures/xhr.html')
.then((responseText) => {
expect(responseText).to.eq('replaced the body')
})
})
.wait('@foo').its('response.body').should('eq', 'replaced the body')
})
// @see https://github.com/cypress-io/cypress/issues/8487
it('different origin (HTTPS)', function () {
const url = uniqueRoute('/foo')
cy.intercept(`${url}*`, 'somethin').as('foo')
.then(() => {
$.get(`https://bar.foobar.com.invalid:3502${url}`)
})
.wait('@foo')
})
it('different origin with response interception (HTTPS)', function () {
cy.intercept('/fixtures/xhr.html*', (req) => {
req.reply((res) => {
expect(res.body).to.include('xhr fixture')
res.body = 'replaced the body'
})
}).as('foo')
.then(() => {
return $.get('https://bar.foobar.com:3502/fixtures/xhr.html')
.then((responseText) => {