This repository was archived by the owner on Feb 20, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathyesno.spec.ts
826 lines (666 loc) · 26.6 KB
/
yesno.spec.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
import { expect } from 'chai';
import * as fse from 'fs-extra';
import _ from 'lodash';
import * as path from 'path';
import rp from 'request-promise';
import rimraf = require('rimraf');
import * as sinon from 'sinon';
import { SinonSandbox as Sandbox } from 'sinon';
import yesno from '../../src';
import { YESNO_RECORDING_MODE_ENV_VAR } from '../../src/consts';
import { IHttpMock } from '../../src/file';
import { ComparatorFn, IComparatorMetadata } from '../../src/filtering/comparator';
import { ISerializedRequest } from '../../src/http-serializer';
import { RecordMode } from '../../src/recording';
import { RuleType } from '../../src/rule';
import * as testServer from '../test-server';
type PartialDeep<T> = { [P in keyof T]?: PartialDeep<T[P]> };
describe('Yesno', () => {
const dir: string = path.join(__dirname, 'tmp');
const mocksDir = path.join(__dirname, 'mocks');
let server: testServer.ITestServer;
const sandbox: Sandbox = sinon.createSandbox();
afterEach(async () => {
sandbox.restore();
await new Promise((res, rej) => rimraf(`${__dirname}/tmp/*`, (e) => (e ? rej(e) : res())));
});
/**
* Make a request to the local test server. Defaults to `/get`
* @param options Request lib options
*/
function requestTestServer(options: object = {}) {
return rp({
method: 'GET',
uri: testServer.URI_ENDPOINT_GET,
...options,
});
}
/**
* Make a request matching the `mock-test` file
*
* Defaults to `example.com`
* @param options Request lib options
*/
function mockedRequest(options: object = {}) {
return rp({
headers: {
'x-fiz': 'baz',
},
method: 'POST',
uri: 'http://example.com/my/path',
...options,
});
}
/**
* Make a mocked response
*
* @param options to override the default response values
*/
function createMock(options: PartialDeep<IHttpMock> = {}): IHttpMock {
return _.merge(
{
request: {
host: 'localhost',
method: 'GET',
path: '/get',
port: 3001,
protocol: 'http',
},
response: {
body: 'foobar',
statusCode: 200,
},
},
options,
) as IHttpMock;
}
before(async () => {
server = await testServer.start();
});
afterEach(() => {
yesno.restore();
});
after(() => {
server.close();
});
describe('#restore', () => {
it('should restore normal HTTP functionality after mocking', async () => {
const startingRequestCount = server.getRequestCount();
await requestTestServer();
expect(server.getRequestCount(), 'Unmocked').to.eql(startingRequestCount + 1);
yesno.mock(await yesno.load({ filename: `${mocksDir}/mock-localhost-get-yesno.json` }));
await requestTestServer();
expect(server.getRequestCount(), 'Mocked').to.eql(startingRequestCount + 1);
yesno.restore();
await requestTestServer();
expect(server.getRequestCount(), 'Unmocked again').to.eql(startingRequestCount + 2);
await yesno.mock(await yesno.load({ filename: `${mocksDir}/mock-localhost-get-yesno.json` }));
await requestTestServer();
expect(server.getRequestCount(), 'Mocked again').to.eql(startingRequestCount + 2);
});
});
describe('#spy', () => {
it('should enable the interceptor');
it('should give us access to intercepted requests');
it('should handle timeouts');
it('should handle invalid SSL');
it('should support application/json');
it('should support application/x-www-form-url-encoded');
it('should proxy status code', async () => {
yesno.spy();
const response = await rp({
headers: { 'x-status-code': 201 },
method: 'GET',
resolveWithFullResponse: true,
uri: 'http://localhost:3001/get',
});
// verify both the proxied and intercepted response
expect(response).to.have.property('statusCode', 201);
expect(yesno.matching(/get/).response()).to.have.property('statusCode', 201);
});
it('should proxy headers', async () => {
yesno.spy();
const response = await rp({
method: 'GET',
resolveWithFullResponse: true,
uri: 'http://localhost:3001/get',
});
// verify both the proxied and intercepted response
expect(response).to.have.nested.property('headers.x-test-server-header', 'foo');
expect(yesno.matching(/get/).response()).to.have.nested.property(
'headers.x-test-server-header',
'foo',
);
});
it('should support multipart/form-data', async () => {
yesno.spy();
await rp({
formData: {
fooBuffer: Buffer.from('foo-buffer'),
fooString: 'foobar-string',
},
method: 'POST',
uri: 'http://localhost:3001/post',
});
const intercepted = yesno.intercepted();
expect(intercepted).to.have.lengthOf(1);
expect(intercepted[0].request.body).to.match(
/Content-Disposition: form-data; name="fooString"\s+foobar-string/,
);
expect(intercepted[0].request.body).to.match(
/Content-Disposition: form-data; name="fooBuffer"\s+Content-Type: application\/octet-stream\s+foo-buffer/,
);
});
it('should send headers for form-data', async () => {
yesno.spy();
await rp({
formData: {
fooBuffer: Buffer.from('foo-buffer'),
fooString: 'foobar-string',
},
headers: { 'x-test-header': 'foo' },
method: 'POST',
uri: 'http://localhost:3001/post',
});
const intercepted = yesno.intercepted();
expect(intercepted).to.have.lengthOf(1);
expect(intercepted[0]).to.have.nested.property('request.headers.x-test-header', 'foo');
expect(intercepted[0]).to.have.nested.property('response.body.headers.x-test-header', 'foo');
});
it('should support binary');
});
describe('#mock', () => {
beforeEach(async () => {
await yesno.mock(await yesno.load({ filename: `${mocksDir}/mock-test-yesno.json` }));
});
afterEach(() => {
yesno.clear();
});
it('should fulfil a matching request', async () => {
const response = await mockedRequest();
expect(response).to.eql('mock body');
});
it('should allow providing mocks', async () => {
yesno.mock([createMock()]);
expect(yesno.intercepted()).to.have.lengthOf(0);
const response = await requestTestServer();
expect(response).to.eql('foobar');
expect(yesno.intercepted()).to.have.lengthOf(1);
});
it('should replace the mocks on subsequent calls but preserve existing intercepted requests');
it('should throw an error if a mock shape is invalid', () => {
const mocks = [
createMock({ response: { body: 'a' } }),
createMock({ response: { body: 'b' } }),
];
(mocks[0] as any).request.host = undefined;
expect(() => yesno.mock(mocks)).to.throw(
'YesNo: Invalid serialized HTTP. (Errors: Expecting Readonly<string> at 0.request.host but instead got: undefined.)',
);
});
it('should allow providing mocks with JSON response bodies as objects', async () => {
yesno.mock([
createMock({
response: {
body: { foo: 'bar' },
},
}),
]);
expect(yesno.intercepted()).to.have.lengthOf(0);
expect(await requestTestServer({ json: true })).to.eql({ foo: 'bar' });
expect(yesno.intercepted()).to.have.lengthOf(1);
});
it('should reject a request for which no mock has been provided');
it('should handle unexpected errors');
it('should reject for host mismatch', async () => {
await expect(mockedRequest({ uri: 'http://foobar.com/my/path' })).to.be.rejectedWith(
/YesNo: Request does not match mock. Expected host "example.com" for request #0, received "foobar.com"/,
);
});
it('should reject for method mismatch', async () => {
await expect(mockedRequest({ method: 'GET' })).to.be.rejectedWith(
/YesNo: Request does not match mock. Expected request #0 for example.com\/my\/path to HTTP method "POST", not "GET"/,
);
});
it('should reject for HTTP protocol mismatch', async () => {
await expect(mockedRequest({ uri: 'https://example.com/my/path' })).to.be.rejectedWith(
/YesNo: Request does not match mock. Expected request #0 for example.com to use "http" protocol, not "https"/,
);
});
it('should reject for port mismatch', async () => {
await expect(mockedRequest({ uri: 'http://example.com:443/my/path' })).to.be.rejectedWith(
/YesNo: Request does not match mock. Expected request #0 for example.com to be served on port "80", not "443"/,
);
});
it('should reject for path mismatch', async () => {
await expect(mockedRequest({ uri: 'http://example.com/my/foobar' })).to.be.rejectedWith(
/Request does not match mock. Expected request #0 "POST http:\/\/example.com:80" to have path "\/my\/path", not "\/my\/foobar"/,
);
});
it('should accept an optional comparatorFn, which can throw to reject a mock', async () => {
const mockErrorMessage = 'some-error';
const mockError = new Error(mockErrorMessage);
const comparatorFn: ComparatorFn = (
intercepted: ISerializedRequest,
mock: ISerializedRequest,
metadata: IComparatorMetadata,
): boolean => {
throw mockError;
};
yesno.mock([createMock()], { comparatorFn });
await expect(requestTestServer()).rejectedWith(mockErrorMessage);
});
it('should accept an optional comparatorFn, which can accept a mock when it does not throw', async () => {
const comparatorFn: ComparatorFn = (
intercepted: ISerializedRequest,
mock: ISerializedRequest,
metadata: IComparatorMetadata,
): boolean => {
return true;
};
yesno.mock([createMock()], { comparatorFn });
expect(yesno.intercepted()).to.have.lengthOf(0);
const response = await requestTestServer();
expect(response).to.eql('foobar');
expect(yesno.intercepted()).to.have.lengthOf(1);
});
it('should override the "content-length" header in the server response if incorrect', async () => {
const mocks = await yesno.load({ filename: `${mocksDir}/mock-x-www-form-urlencoded.json` });
const mockContentLength = mocks[0].response.headers['content-length'];
expect(mockContentLength).to.eql('999999999');
yesno.mock(mocks);
const response = await rp({
form: {
description: 'YesNo test',
},
method: 'POST',
resolveWithFullResponse: true,
uri: 'https://example.com/my/path',
});
const intercepted = yesno.intercepted();
expect(intercepted).to.have.lengthOf(1);
const overriddenContentLength = response.headers['content-length'];
expect(overriddenContentLength).to.be.ok;
expect(overriddenContentLength, 'Had to override content length').to.not.eql(
mockContentLength,
);
});
});
describe('#recording', () => {
describe('if "spy" mode', () => {
const filename = path.join(__dirname, 'tmp', 'recording-spy.json');
before(() => (process.env[YESNO_RECORDING_MODE_ENV_VAR] = RecordMode.Spy));
it('should make live requests', async () => {
await yesno.recording({ filename });
const reqCount = server.getRequestCount();
await requestTestServer();
expect(yesno.intercepted()).to.have.lengthOf(1);
expect(server.getRequestCount()).to.eql(reqCount + 1);
});
it('should not persist the recording', async () => {
const recording = await yesno.recording({ filename });
await requestTestServer();
await recording.complete();
expect(fse.existsSync(filename)).to.be.false;
});
});
describe('if "record" mode', () => {
const filename = path.join(__dirname, 'tmp', 'recording-record.json');
before(() => (process.env[YESNO_RECORDING_MODE_ENV_VAR] = RecordMode.Record));
it('should make live requests', async () => {
await yesno.recording({ filename });
const reqCount = server.getRequestCount();
await requestTestServer();
expect(yesno.intercepted()).to.have.lengthOf(1);
expect(server.getRequestCount()).to.eql(reqCount + 1);
});
it('should persist the recording', async () => {
const recording = await yesno.recording({ filename });
await requestTestServer();
await recording.complete();
expect(fse.existsSync(filename)).to.be.true;
});
});
describe('if "mock" mode', () => {
const filename = path.join(__dirname, 'mocks', 'recording-mock.json');
before(() => (process.env[YESNO_RECORDING_MODE_ENV_VAR] = RecordMode.Mock));
it('should mock responses', async () => {
await yesno.recording({ filename });
const reqCount = server.getRequestCount();
await requestTestServer();
expect(yesno.intercepted()).to.have.lengthOf(1);
expect(server.getRequestCount()).to.eql(reqCount);
});
it('should not persist the recording', async () => {
const tmpFilename = path.join(__dirname, 'tmp', 'recording-mock.json');
await fse.writeFile(tmpFilename, await fse.readFileSync(filename));
const recording = await yesno.recording({ filename: tmpFilename });
await fse.unlink(tmpFilename); // Delete fixtures, so that we can verify new ones aren't persisted
await requestTestServer();
await recording.complete();
expect(fse.existsSync(tmpFilename)).to.be.false;
});
});
});
describe('#mockRule', () => {
const ctx = 'ctx';
beforeEach(() => {
yesno.mock([createMock({ response: { body: 'mocked' } })]);
});
afterEach(() => {
yesno.clear();
yesno[ctx].rules = [];
});
it('should add a rule with defaults', async () => {
await yesno.mockRule('http://localhost/get');
expect(yesno[ctx].rules).to.have.lengthOf(1);
expect(yesno[ctx].rules[0].ruleType).to.equal(RuleType.Record);
// verify the mocked response
const response = await requestTestServer();
expect(response).to.equal('mocked');
});
it('should add a rule with type RECORD', async () => {
await yesno.mockRule('http://localhost/get').record();
expect(yesno[ctx].rules).to.have.lengthOf(1);
expect(yesno[ctx].rules[0].ruleType).to.equal(RuleType.Record);
// verify the mocked response
const response = await requestTestServer();
expect(response).to.equal('mocked');
});
it('should add a rule with type LIVE', async () => {
await yesno.mockRule('http://localhost/get').live();
expect(yesno[ctx].rules).to.have.lengthOf(1);
expect(yesno[ctx].rules[0].ruleType).to.equal(RuleType.Live);
// verify the proxied response
const response = await requestTestServer({ json: true });
expect(response.source).to.equal('server');
});
it('should add a rule with type RESPOND', async () => {
await yesno.mockRule('http://localhost/get').respond({
body: 'mockRespond',
statusCode: 200,
});
expect(yesno[ctx].rules).to.have.lengthOf(1);
expect(yesno[ctx].rules[0].ruleType).to.equal(RuleType.Respond);
// verify the custom mock response
const response = await requestTestServer();
expect(response).to.equal('mockRespond');
});
});
describe('#test', () => {
beforeEach(() => {
process.env[YESNO_RECORDING_MODE_ENV_VAR] = RecordMode.Spy;
});
it('should create a recordable test', async () => {
process.env[YESNO_RECORDING_MODE_ENV_VAR] = RecordMode.Record;
const mockTestFn = sandbox.mock(); // eg jest.test
const mockTest = sandbox.mock();
const expectedFilename = `${dir}/test-title-yesno.json`;
const expectedFilenamePrefix = `${dir}/foobar-test-title-yesno.json`;
const recordedTest = yesno.test({ test: mockTestFn, dir });
const recordedTestPrefix = yesno.test({ test: mockTestFn, dir, prefix: 'foobar' });
recordedTest('test title', mockTest);
expect(mockTestFn).to.have.been.calledOnceWith('test title');
expect(fse.existsSync(expectedFilename)).to.be.false;
expect(fse.existsSync(expectedFilenamePrefix)).to.be.false;
expect(mockTest).to.not.have.been.called;
const callback = mockTestFn.args[0][1];
await callback();
expect(mockTest).to.have.been.calledOnce;
expect(fse.existsSync(expectedFilename)).to.be.true;
mockTestFn.reset();
mockTest.reset();
recordedTestPrefix('test title', mockTest);
const callbackPrefix = mockTestFn.args[0][1];
await callbackPrefix();
expect(fse.existsSync(expectedFilenamePrefix)).to.be.true;
});
it('should restore behavior before and after the test regardless of whether it passes', async () => {
const mockTestFn = sandbox.mock(); // eg jest.test
const mockTest = sandbox.mock().resolves();
const mockTestReject = sandbox.mock().rejects(new Error('Mock reject'));
const mockTestThrow = sandbox.mock().throws(new Error('Mock throw'));
const restoreSpy = sandbox.spy(yesno, 'restore');
const recordedTest = yesno.test({ test: mockTestFn, dir });
// Success
recordedTest('test success', mockTest);
const successTestCallback = mockTestFn.args[0][1];
mockTestFn.reset();
expect(restoreSpy).to.have.callCount(0);
await successTestCallback();
expect(restoreSpy).to.have.callCount(2);
restoreSpy.resetHistory();
// Rejected
recordedTest('test reject', mockTestReject);
const rejectTestCallback = mockTestFn.args[0][1];
mockTestFn.reset();
expect(restoreSpy).to.have.callCount(0);
await expect(rejectTestCallback()).to.be.rejectedWith('Mock reject');
expect(restoreSpy).to.have.callCount(2);
restoreSpy.resetHistory();
// Thrown
recordedTest('test throw', mockTestThrow);
const throwTestCallback = mockTestFn.args[0][1];
mockTestFn.reset();
expect(restoreSpy).to.have.callCount(0);
await expect(throwTestCallback()).to.be.rejectedWith('Mock throw');
expect(restoreSpy).to.have.callCount(2);
restoreSpy.resetHistory();
});
});
describe('#save', () => {
const mockRequest = {
body: {},
headers: {},
host: 'test',
method: 'GET',
path: '/',
port: 80,
protocol: 'http',
};
it('should create the directory if it does not exist', async () => {
const nestedDir = `${__dirname}/tmp/my/dir`;
const filename = `${nestedDir}/file.json`;
expect(fse.existsSync(nestedDir)).to.be.false;
expect(fse.existsSync(filename)).to.be.false;
await yesno.save({ filename });
expect(fse.existsSync(filename)).to.be.true;
});
it('should save intercepted requests');
it('should throw an error if there are any in flight requests', async () => {
const ctx = 'ctx';
const nestedDir = `${__dirname}/tmp/save/dir`;
const filename = `${nestedDir}/file.json`;
expect(fse.existsSync(nestedDir)).to.be.false;
expect(fse.existsSync(filename)).to.be.false;
Object.defineProperty(yesno[ctx], 'inFlightRequests', [
{
requestSerializer: mockRequest,
startTime: null,
},
]);
try {
expect(async () => await yesno.save({ filename })).to.throw(
'Error: YesNo: Cannot save. Still have 1 in flight requests',
);
} catch (e) {
Object.defineProperty(yesno[ctx], 'inFlightRequests', []);
}
});
it('should allow force save with in flight requests', async () => {
const ctx = 'ctx';
const nestedDir = `${__dirname}/tmp/save/dir`;
const filename = `${nestedDir}/file.json`;
expect(fse.existsSync(nestedDir)).to.be.false;
expect(fse.existsSync(filename)).to.be.false;
Object.defineProperty(yesno[ctx], 'inFlightRequests', [
{
requestSerializer: mockRequest,
startTime: null,
},
]);
await yesno.save({ filename, force: true });
expect(fse.existsSync(filename)).to.be.true;
Object.defineProperty(yesno[ctx], 'inFlightRequests', []);
});
it('should take no action in mock mode (if not provided requests)');
it('should allow setting the full filename');
it('should allow providing the records');
});
describe('#load', () => {
it('should load serialized requests by name & dir');
it('should load serialized requests by filename');
it('should support application/json');
it('should support x-www-form-url-encoded');
it('should support binary');
it('should support form-data');
it('should throw an error if a record is not formatted correctly');
});
describe('#intercepted', () => {
it('should call FilteredHttpCollection#intercepted() with no query');
});
describe('#mocks', () => {
it('should call FilteredHttpCollection#mocks() with no query');
});
describe('#redact', () => {
it('should call FilteredHttpCollection#redact() with no query');
});
describe('#matching', () => {
it('should call FilteredHttpCollection#redact() with the provided query');
it('should allow for no parameters', async () => {
yesno.spy();
await expect(requestTestServer({ headers: { 'x-status-code': 500 } })).to.be.rejected;
expect(yesno.matching().response()).to.have.property('statusCode', 500);
});
describe('#respond', () => {
it('allows defining mocks statically', async () => {
yesno.spy();
const unmockedResponse = await requestTestServer({
json: true,
resolveWithFullResponse: true,
simple: false,
});
expect(unmockedResponse).to.have.property('statusCode', 200);
yesno
.matching({ request: { path: '/get' } })
.respond({ statusCode: 400, headers: { 'x-fiz': 'baz' }, body: { foo: 'bar' } });
const mockedResponse = await requestTestServer({
json: true,
resolveWithFullResponse: true,
simple: false,
});
expect(mockedResponse).to.have.property('statusCode', 400);
expect(mockedResponse).to.have.deep.property('body', { foo: 'bar' });
expect(mockedResponse).to.have.nested.property('headers.x-fiz', 'baz');
});
it('allows defining mocks dynamically', async () => {
yesno.spy();
yesno
.matching({ request: { path: '/post' } })
.respond((request) => ({ statusCode: 401, body: request.body }));
const body = { now: Date.now(), random: Math.random() };
const mockedResponse = await requestTestServer({
body,
json: true,
method: 'post',
resolveWithFullResponse: true,
simple: false,
uri: testServer.URI_ENDPOINT_POST,
});
expect(mockedResponse).to.have.property('statusCode', 401);
expect(mockedResponse).to.have.deep.property('body', body);
});
it('should support mock override with respond', async () => {
yesno.mock([
createMock({ response: { body: 'a' } }),
createMock({ response: { body: 'b' } }),
createMock({ response: { body: 'c' } }),
]);
yesno.matching({ request: { path: '/test' } }).respond({
body: 'fizbaz',
statusCode: 200,
});
expect(yesno.intercepted()).to.have.lengthOf(0);
// consumes first mock
let response = await requestTestServer();
expect(response).to.eql('a');
expect(yesno.intercepted()).to.have.lengthOf(1);
// consumes matched mock
response = await requestTestServer({ uri: 'http://localhost/test' });
expect(response).to.eql('fizbaz');
expect(yesno.intercepted()).to.have.lengthOf(2);
// consumes third mock
response = await requestTestServer();
expect(response).to.eql('c');
expect(yesno.intercepted()).to.have.lengthOf(3);
});
});
describe('#ignore', () => {
it('allows ignoring a mocked url', async () => {
yesno.mock([
createMock({ response: { body: 'a' } }),
createMock({ response: { body: 'b' } }),
createMock({ response: { body: 'c' } }),
]);
// verify the mocked response
let response = await requestTestServer({
json: true,
resolveWithFullResponse: true,
simple: false,
});
expect(response).to.have.property('statusCode', 200);
expect(response).to.have.property('body', 'a');
// add the ignore filter
yesno.matching({ request: { path: '/get' } }).ignore();
// verify the unmocked response
response = await requestTestServer({
json: true,
resolveWithFullResponse: true,
simple: false,
});
expect(response).to.have.property('statusCode', 200);
expect(response).to.have.nested.property('body.headers.host', 'localhost:3001');
expect(response).to.have.nested.property('body.source', 'server');
// verify the response continues to be unmocked
response = await requestTestServer({
json: true,
resolveWithFullResponse: true,
simple: false,
});
expect(response).to.have.property('statusCode', 200);
expect(response).to.have.nested.property('body.headers.host', 'localhost:3001');
expect(response).to.have.nested.property('body.source', 'server');
});
it('allows ignoring a mocked url defined with .respond', async () => {
yesno.mock([
createMock({ response: { body: 'a' } }),
createMock({ response: { body: 'b' } }),
]);
// set mock override with respond
yesno
.matching({ request: { path: '/get' } })
.respond({ statusCode: 400, body: { foo: 'bar' } });
// verify the overriden mocked response
let response = await requestTestServer({
json: true,
resolveWithFullResponse: true,
simple: false,
});
expect(response).to.have.property('statusCode', 400);
expect(response).to.have.deep.property('body', { foo: 'bar' });
// add the ignore filter
yesno.matching({ request: { path: '/get' } }).ignore();
// verify the unmocked response
response = await requestTestServer({
json: true,
resolveWithFullResponse: true,
simple: false,
});
expect(response).to.have.property('statusCode', 200);
expect(response).to.have.nested.property('body.headers.host', 'localhost:3001');
expect(response).to.have.nested.property('body.source', 'server');
});
});
});
});