-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathnode.spec.js
630 lines (562 loc) · 22.3 KB
/
node.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
// Mocha Specification Suite
// Run on a node server
// Imports
import { assertDeepStrictEqual } from 'assert-deep-strict-equal';
import assert from 'assert';
// Setup
import { fetchJson, FetchJson } from '../dist/fetch-json.js';
const mode = { type: 'ES Module', file: 'dist/fetch-json.js' };
const filename = import.meta.url.replace(/.*\//, ''); //jshint ignore:line
// Specification suite
describe(`Specifications: ${filename} - ${mode.type} (${mode.file})`, () => {
// Synchronize all changes below this line with the suite in: jsdom.spec.js
////////////////////////////////////////////////////////////////////////////////
describe('Module fetch-json', () => {
it('follows semantic versioning', () => {
const semVerPattern = /\d+[.]\d+[.]\d+/;
const actual = { version: fetchJson.version, valid: semVerPattern.test(fetchJson.version) };
const expected = { version: fetchJson.version, valid: true };
assertDeepStrictEqual(actual, expected);
});
it('loads as an object', () => {
const actual = { module: typeof fetchJson };
const expected = { module: 'object' };
assertDeepStrictEqual(actual, expected);
});
it('has functions for get(), post(), put(), patch(), and delete()', () => {
const actual = {
get: typeof fetchJson.get,
post: typeof fetchJson.post,
put: typeof fetchJson.put,
patch: typeof fetchJson.patch,
delete: typeof fetchJson.delete,
};
const expected = {
get: 'function',
post: 'function',
put: 'function',
patch: 'function',
delete: 'function',
};
assertDeepStrictEqual(actual, expected);
});
});
////////////////////////////////////////////////////////////////////////////////
describe('Google Books API search result for "spacex" fetched by fetchJson.get()', () => {
it('contains the correct "kind" value and "totalItems" as a number', (done) => {
const url = 'https://www.googleapis.com/books/v1/volumes?q=spacex';
const handleData = (data) => {
const actual = { total: typeof data.totalItems, kind: data.kind };
const expected = { total: 'number', kind: 'books#volumes' };
assertDeepStrictEqual(actual, expected, done);
};
fetchJson.get(url).then(handleData);
});
});
////////////////////////////////////////////////////////////////////////////////
describe('Star Wars API result for spaceships fetched by fetchJson.get()', () => {
it('contains an array of spaceships', (done) => {
const url = 'https://swapi.py4e.com/api/starships/';
const params = { format: 'json' };
const handleData = (data) => {
const actual = { count: typeof data.count, class: typeof data.results[0].starship_class };
const expected = { count: 'number', class: 'string' };
assertDeepStrictEqual(actual, expected, done);
};
fetchJson.get(url, params).then(handleData);
});
});
////////////////////////////////////////////////////////////////////////////////
describe('Awaiting a berry from the PokéAPI with fetchJson.get() [async/await]', () => {
it('is rewarded with a tasty treat', async () => {
const url = 'https://pokeapi.co/api/v2/berry/razz';
const data = await fetchJson.get(url);
const actual = { id: data.id, name: data.name, growth_time: data.growth_time };
const expected = { id: 16, name: 'razz', growth_time: 2 };
assertDeepStrictEqual(actual, expected);
});
});
////////////////////////////////////////////////////////////////////////////////
describe('GET response returned by HTTP echo service', () => {
it('contains empty params when none are supplied', (done) => {
const url = 'https://centerkey.com/rest/';
const handleData = (actual) => {
delete actual.headers;
const expected = {
method: 'GET',
query: '',
params: {},
body: null,
};
assertDeepStrictEqual(actual, expected, done);
};
fetchJson.get(url).then(handleData);
});
it('contains the params from the URL query string', (done) => {
const url = 'https://centerkey.com/rest/?planet=Jupiter&position=5';
const handleData = (actual) => {
delete actual.headers;
const expected = {
method: 'GET',
query: 'planet=Jupiter&position=5',
params: { planet: 'Jupiter', position: '5' },
body: null,
};
assertDeepStrictEqual(actual, expected, done);
};
fetchJson.get(url).then(handleData);
});
it('contains the params from an object', (done) => {
const url = 'https://centerkey.com/rest/';
const params = { planet: 'Jupiter', position: 5, tip: 'Big & -148°C' };
const handleData = (actual) => {
delete actual.headers;
const expected = {
method: 'GET',
query: 'planet=Jupiter&position=5&tip=Big%20%26%20-148%C2%B0C',
params: { planet: 'Jupiter', position: '5', tip: 'Big & -148°C' },
body: null,
};
assertDeepStrictEqual(actual, expected, done);
};
fetchJson.get(url, params).then(handleData);
});
it('contains the params from both the URL query string and an object', (done) => {
const url = 'https://centerkey.com/rest/?sort=diameter';
const params = { planet: 'Jupiter', position: 5 };
const handleData = (actual) => {
delete actual.headers;
const expected = {
method: 'GET',
query: 'sort=diameter&planet=Jupiter&position=5',
params: { sort: 'diameter', planet: 'Jupiter', position: '5' },
body: null,
};
assertDeepStrictEqual(actual, expected, done);
};
fetchJson.get(url, params).then(handleData);
});
});
////////////////////////////////////////////////////////////////////////////////
describe('Response returned by HTTP echo service for a planet (object literal)', () => {
it('from a POST contains the planet (JSON)', (done) => {
const url = 'https://centerkey.com/rest/';
const resource = { name: 'Mercury', position: 1 };
const handleData = (actual) => {
delete actual.headers;
const expected = {
method: 'POST',
query: '',
params: {},
body: resource,
};
assertDeepStrictEqual(actual, expected, done);
};
fetchJson.post(url, resource).then(handleData);
});
it('from a PUT contains the planet (JSON)', (done) => {
const url = 'https://centerkey.com/rest/';
const resource = { name: 'Venus', position: 2 };
const handleData = (actual) => {
delete actual.headers;
const expected = {
method: 'PUT',
query: '',
params: {},
body: resource,
};
assertDeepStrictEqual(actual, expected, done);
};
fetchJson.put(url, resource).then(handleData);
});
it('from a PATCH contains the planet (JSON)', (done) => {
const url = 'https://centerkey.com/rest/';
const resource = { name: 'Mars', position: 4 };
const handleData = (actual) => {
delete actual.headers;
const expected = {
method: 'PATCH',
query: '',
params: {},
body: resource,
};
assertDeepStrictEqual(actual, expected, done);
};
fetchJson.patch(url, resource).then(handleData);
});
it('from a DELETE contains the planet (JSON)', (done) => {
const url = 'https://centerkey.com/rest/';
const resource = { name: 'Jupiter', position: 5 };
const handleData = (actual) => {
delete actual.headers;
const expected = {
method: 'DELETE',
query: '',
params: {},
body: resource,
};
assertDeepStrictEqual(actual, expected, done);
};
fetchJson.delete(url, resource).then(handleData);
});
});
////////////////////////////////////////////////////////////////////////////////
describe('HEAD response for a Figy Berry from the PokéAPI', () => {
it('contains the correct headers', (done) => {
const url = 'https://pokeapi.co/api/v2/berry/figy';
const handleData = (data) => {
const actual = {
'content-type': data['content-type'],
'cache-control': data['cache-control'],
};
const expected = {
'content-type': 'application/json; charset=utf-8',
'cache-control': 'public, max-age=86400, s-maxage=86400',
};
assertDeepStrictEqual(actual, expected, done);
};
fetchJson.head(url).then(handleData);
});
});
////////////////////////////////////////////////////////////////////////////////
describe('The low-level fetchJson.request() function', () => {
it('can successfully GET a planet', (done) => {
const url = 'https://centerkey.com/rest/';
const params = { planet: 'Neptune', position: 8 };
const handleData = (actual) => {
delete actual.headers;
const expected = {
method: 'GET',
query: 'planet=Neptune&position=8',
params: { planet: 'Neptune', position: '8' },
body: null,
};
assertDeepStrictEqual(actual, expected, done);
};
fetchJson.request('GET', url, params).then(handleData);
});
it('can successfully POST a planet', (done) => {
const url = 'https://centerkey.com/rest/';
const resource = { name: 'Saturn', position: 6 };
const handleData = (actual) => {
delete actual.headers;
const expected = {
method: 'POST',
query: '',
params: {},
body: resource,
};
assertDeepStrictEqual(actual, expected, done);
};
fetchJson.request('POST', url, resource).then(handleData);
});
});
////////////////////////////////////////////////////////////////////////////////
describe('HTTP error returned by the server', () => {
it('for status 500 contains the message "Internal Server Error"', (done) => {
const url = 'https://centerkey.com/rest/status/500/';
const handleData = (actual) => {
delete actual.response;
const expected = {
ok: false,
error: true,
status: 500,
contentType: 'text/plain;charset=UTF-8',
bodyText: 'Whoa. Deja vu.\n',
data: null,
};
assertDeepStrictEqual(actual, expected, done);
};
const handleError = (error) => {
assert.fail(error);
};
fetchJson.enableLogger();
fetchJson.get(url).then(handleData).catch(handleError);
});
it('for status 500 throws exception in strict errors mode', (done) => {
const url = 'https://centerkey.com/rest/status/500/';
const handleData = (data) => {
assert.fail(data);
};
const handleError = (error) => {
const actual = {
object: error.constructor.name,
name: error.name,
message: error.message,
};
const expected = {
object: 'Error',
name: 'Error',
message: '[fetch-json] HTTP response status ("strictErrors" mode enabled): 500',
};
assertDeepStrictEqual(actual, expected, done);
};
fetchJson.get(url, {}, { strictErrors: true }).then(handleData).catch(handleError);
});
it('for status 418 contains the message "I\'m a teapot"', (done) => {
const url = 'https://centerkey.com/rest/status/418/'; //trailing slash to prevent redirect
const handleData = (actual) => {
console.log(actual.bodyText);
delete actual.bodyText;
delete actual.response;
const expected = {
ok: false,
error: true,
status: 418,
contentType: 'text/plain;charset=UTF-8',
data: null,
};
assertDeepStrictEqual(actual, expected, done);
};
const handleError = (error) => {
assert.fail(error);
};
fetchJson.get(url).then(handleData).catch(handleError);
});
});
////////////////////////////////////////////////////////////////////////////////
describe('The "bodyText" field of the object returned from requesting', () => {
const getFirstLine = (string) => string.split('\n', 1)[0];
it('an HTML web page is a string that begins with "<!doctype html>"', (done) => {
const url = 'https://pretty-print-json.js.org';
const handleData = (data) => {
const actual = {
ok: data.ok,
status: [data.status, data.response.statusText],
contentType: data.contentType,
firstLine: getFirstLine(data.bodyText),
data: data.data,
};
const expected = {
ok: true,
status: [200, 'OK'],
contentType: 'text/html; charset=utf-8',
firstLine: '<!doctype html>',
data: null,
};
assertDeepStrictEqual(actual, expected, done);
};
fetchJson.get(url).then(handleData);
});
it('an XML document is a string that begins with the <?xml> tag', (done) => {
const url = 'https://centerkey.com/rest/';
const handleData = (actual) => {
actual.bodyText = getFirstLine(actual.bodyText); //just verify first line
delete actual.response;
const expected = {
ok: true,
error: false,
status: 200,
contentType: 'application/xml',
bodyText: '<?xml version="1.0" encoding="utf-8"?>',
data: null,
};
assertDeepStrictEqual(actual, expected, done);
};
const getXml = { headers: { Accept: 'application/xml' }};
fetchJson.get(url, {}, getXml).then(handleData);
});
it('a plain text file is a string with the correct first word', (done) => {
const url = 'https://centerkey.com/rest/';
const handleData = (actual) => {
actual.bodyText = getFirstLine(actual.bodyText); //just verify first line
delete actual.response;
const expected = {
ok: true,
error: false,
status: 200,
contentType: 'text/plain;charset=UTF-8',
bodyText: '{',
data: null,
};
assertDeepStrictEqual(actual, expected, done);
};
const getText = { headers: { Accept: 'text/plain' }};
fetchJson.get(url, {}, getText).then(handleData);
});
});
////////////////////////////////////////////////////////////////////////////////
describe('Function fetchJson.enableLogger()', () => {
it('sets the logger to the function passed in', () => {
const mockLogger = () => {};
fetchJson.enableLogger(mockLogger);
const actual = { type: typeof fetchJson.logger, fn: fetchJson.logger };
const expected = { type: 'function', fn: mockLogger };
assertDeepStrictEqual(actual, expected);
});
it('disables the logger when passed false', () => {
fetchJson.disableLogger();
const actual = { logger: fetchJson.logger, disabled: !fetchJson.logger };
const expected = { logger: null, disabled: true };
assertDeepStrictEqual(actual, expected);
});
it('passes a timestamp, methed, and URL to a custom logger on GET', (done) => {
const url = 'https://centerkey.com/rest/';
const headerMap = fetchJson.getLogHeaderIndexMap();
const rawEvents = [];
const toEvent = (rawEvent, index) => ({
event: index,
timestamp: rawEvent[headerMap.timestamp].length,
method: rawEvent[headerMap.method],
domain: rawEvent[headerMap.domain],
url: rawEvent[headerMap.url],
ok: rawEvent[headerMap.ok],
status: rawEvent[headerMap.status],
text: rawEvent[headerMap.text],
type: rawEvent[headerMap.type],
});
const verifyEvents = () => {
fetchJson.disableLogger();
const actual = rawEvents.map(toEvent);
const expected = [
{
event: 0,
timestamp: 24,
method: 'GET',
domain: 'centerkey.com',
url: 'https://centerkey.com/rest/',
ok: undefined,
status: undefined,
text: undefined,
type: undefined,
},
{
event: 1,
timestamp: 24,
method: 'GET',
domain: 'centerkey.com',
url: 'https://centerkey.com/rest/',
ok: true,
status: 200,
text: 'OK',
type: 'application/json',
},
];
assertDeepStrictEqual(actual, expected, done);
};
fetchJson.enableLogger((...rawEvent) => rawEvents.push(rawEvent));
fetchJson.get(url).then(verifyEvents);
});
});
////////////////////////////////////////////////////////////////////////////////
describe('Base options', () => {
it('can be set to automatically add an "Authorization" HTTP header', (done) => {
const url = 'https://centerkey.com/rest/';
const baseOptions = { headers: { Authorization: 'Basic WE1MIGlzIGhpZGVvdXM=' } };
const options = { referrerPolicy: 'no-referrer' };
fetchJson.setBaseOptions(baseOptions);
const handleData = (actual) => {
actual.auth = actual.headers.Authorization ?? null;
delete actual.headers;
const expected = {
auth: 'Basic WE1MIGlzIGhpZGVvdXM=',
method: 'GET',
query: 'planet=Mars',
params: { planet: 'Mars' },
body: null
};
assertDeepStrictEqual(actual, expected, done);
};
fetchJson.get(url, { planet: 'Mars' }, options).then(handleData);
});
it('can be cleared', (done) => {
const url = 'https://centerkey.com/rest/';
fetchJson.setBaseOptions({});
const handleData = (actual) => {
actual.auth = actual.headers.Authorization ?? null;
delete actual.headers;
const expected = {
auth: null,
method: 'GET',
query: 'planet=Mercury',
params: { planet: 'Mercury' },
body: null
};
assertDeepStrictEqual(actual, expected, done);
};
fetchJson.get(url, { planet: 'Mercury' }).then(handleData);
});
});
////////////////////////////////////////////////////////////////////////////////
describe('FetchJson class instances', () => {
it('can each set different base options', (done) => {
const url = 'https://centerkey.com/rest/';
const baseOptionsA = { headers: { From: '[email protected]' } };
const baseOptionsB = { headers: { From: '[email protected]' } };
const fetchJsonA = new FetchJson(baseOptionsA).fetchJson;
const fetchJsonB = new FetchJson(baseOptionsB).fetchJson;
const handleData = (actual) => {
actual.push([actual[0].headers.From, actual[1].headers.From]);
delete actual[0].headers;
delete actual[1].headers;
const expected = [
{
method: 'GET',
query: 'planet=Venus',
params: { planet: 'Venus' },
body: null
},
{
method: 'GET',
query: 'planet=Earth',
params: { planet: 'Earth' },
body: null
},
['[email protected]', '[email protected]'],
];
assertDeepStrictEqual(actual, expected, done);
};
const promiseA = fetchJsonA.get(url, { planet: 'Venus' });
const promiseB = fetchJsonB.get(url, { planet: 'Earth' });
Promise.all([promiseA, promiseB]).then(handleData);
});
});
////////////////////////////////////////////////////////////////////////////////
describe('Correct error is thrown', () => {
it('when the HTTP method is missing', () => {
const makeBogusRequest = () => fetchJson.request(null, 'http://example.com');
const exception = { message: '[fetch-json] HTTP method missing or invalid.' };
assert.throws(makeBogusRequest, exception);
});
it('when the HTTP method is invalid', () => {
const makeBogusRequest = () => fetchJson.request(Infinity, 'http://example.com');
const exception = { message: '[fetch-json] HTTP method missing or invalid.' };
assert.throws(makeBogusRequest, exception);
});
it('when the HTTP protocol is bogus', (done) => {
const specEnv = typeof JSDOM === 'function' ? 'jsdom' : 'node';
const message = {
jsdom: 'Network request failed',
node: 'fetch failed',
};
const handleError = (error) => {
const actual = {
object: error.constructor.name,
name: error.name,
message: error.message,
};
const expected = {
object: 'TypeError',
name: 'TypeError',
message: message[specEnv],
};
assertDeepStrictEqual(actual, expected, done);
};
fetchJson.get('bogus://example.com').catch(handleError);
});
it('when the HTTP domain is bogus', (done) => {
const specEnv = typeof JSDOM === 'function' ? 'jsdom' : 'node';
const message = {
jsdom: 'Network request failed',
node: 'fetch failed',
};
const handleError = (error) => {
const actual = { message: error.message };
const expected = { message: message[specEnv] };
assertDeepStrictEqual(actual, expected, done);
};
fetchJson.get('https://bogus.bogus').catch(handleError);
});
});
////////////////////////////////////////////////////////////////////////////////
});