-
Notifications
You must be signed in to change notification settings - Fork 14
/
icedfrisby.js
1352 lines (1221 loc) · 36 KB
/
icedfrisby.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
'use strict'
/*
* IcedFrisby.js
* 2015 Robert Herhold (maintainer) & other wonderful contrubuters
* 2011-2014 Vance Lucas, Brightbit, LLC
*
* IcedFrisby is a library designed to easily test REST API endpoints and their
* responses with node.js and Mocha. It is based on the original Frisby project.
*
* IcedFrisby is distributed under the MIT and BSD licenses
* https://opensource.org/licenses/MIT
* https://opensource.org/licenses/bsd-license
*/
const https = require('https')
const { Stream } = require('stream')
const util = require('util')
const _ = require('lodash')
const chai = require('chai')
const chalk = require('chalk')
const qs = require('qs')
const request = require('request')
const { errorFromList } = require('verror')
const { sleep } = require('wait-promise')
const pkg = require('../package.json')
const pm = require('./pathMatch')
/**
* @param {object} headerName - header name
* @param {object} headers- http headers
* @return {boolean}
* @desc verifies proper headers
*/
function _hasHeader(headername, headers) {
const headerNames = Object.keys(headers || {})
const lowerNames = headerNames.map(function (name) {
return name.toLowerCase()
})
const lowerName = headername.toLowerCase()
for (let i = 0; i < lowerNames.length; i++) {
if (lowerNames[i] === lowerName) return headerNames[i]
}
return false
}
/**
* Parse body as JSON, ensuring not to re-parse when body is already an object
* (thanks @dcaylor).
* @param {object} body - json object
* @return {object}
* @desc parse response body as json
*/
function _jsonParse(body) {
let json = ''
try {
json = typeof body === 'object' ? body : JSON.parse(body)
} catch (e) {
throw new Error(
'Error parsing JSON string: ' + e.message + '\n\tGiven: ' + body
)
}
return json
}
/**
* @param {string} app - Node.js app. (e.g. Express, Koa)
* @param {string} basePath - base path to append to the server address
* @return {Object}
*/
function startApp(app, basePath) {
// coerce basePath to a string
basePath = basePath ? basePath + '' : ''
let server
if (!app.listening) {
server = app.listen()
} else {
server = app
}
const protocol = app instanceof https.Server ? 'https' : 'http'
const port = server.address().port
return {
server,
uri: `${protocol}://127.0.0.1:${port}${basePath}`,
}
}
/**
* IcedFrisby object, uses create() to initialize
*/
module.exports = class Frisby {
static get version() {
return pkg.version
}
/**
* @constructor
* @param {string} message - message to print for it()
* @return {object}
*/
constructor(message) {
// Optional exception handler
this._exceptionHandler = false
Object.assign(this, {
_message: message,
_hooks: {
before: [],
after: [],
finally: [],
},
_inspects: [],
_expects: [],
_failures: [],
_attempts: {
count: 0,
maxRetries: 0,
backoffMillis: 1000,
},
_runner: null,
_requestArgs: null,
_outgoing: null,
_waitsMillis: 0,
_response: {
error: null,
status: null,
headers: [],
body: null,
time: 0,
},
_inspectOnFailure: true,
_requestTimeoutId: undefined,
_requestDidTimeOut: false,
})
// Spec storage
this.current = {
isNot: false, // test negation
// For an app provided to a single test.
app: null,
// Custom vars added to test HTTP Request (like headers)
request: {
headers: {},
json: false,
baseUri: '',
},
}
this.currentRequestFinished = false
this._timeout = 5000
this._only = false
this._skip = false
this._skipWhen = undefined
return this
}
/**
* specify global defaults for IcedFrisby test run
* @param {object} obj - setup object
* @return {object}
* @desc global setup function
*/
static globalSetup() {
throw Error('globalSetup() has been removed.')
}
/**
* Main Frisby method used to start new spec tests
*/
static create(msg) {
// Use `this` instead of `Frisby` so this does the right thing when
// composed with mixins.
return new this(msg)
}
only() {
this._only = true
return this
}
skip() {
this._skip = true
return this
}
skipIf(condition) {
if (condition) {
this._skip = true
}
return this
}
get _shouldSkip() {
return this._skip || (this._skipWhen && this._skipWhen())
}
skipWhen(predicate) {
if (typeof predicate !== 'function') {
throw Error('Expected predicate to be a function')
}
this._skipWhen = predicate
return this
}
/**
* Set the baseUri, replacing any baseUri from global setup
* @param baseUri The new base URI
*/
baseUri(baseUri) {
this.current.request.baseUri = baseUri
return this
}
/**
* @param {string} app - Node.js app. (e.g. Express, Koa)
* @param {string} basePath - base path to append to the server address
* @return {object}
* @desc Setup the request to use a passed in Node http.Server app
*/
useApp(app, basePath) {
if (!app) {
throw new Error('No app provided')
}
this.current.useApp = { app, basePath }
// The app's baseUri won't be known until the app is started. Its uri
// will be prepended then.
this.current.request.baseUri = null
return this
}
/**
* @param {number} ms - timeout value in milliseconds
* @return {object}
* @desc Timeout getter and setter
*/
timeout(ms) {
if (!ms) {
return this._timeout
}
this._timeout = ms
return this
}
/**
* @param {number} count - retry n times
* @param {number} backoffMillis - backoff time for each retry
* @return {object}
* @desc retry the request (good for flaky,slow tests)
*/
retry(count, backoffMillis) {
this._attempts.maxRetries = count
if (typeof backoffMillis !== 'undefined') {
this._attempts.backoffMillis = backoffMillis
}
return this
}
/**
* @param {number} ms - n time in milliseconds
* @return {object}
* @desc time to wait before attempting to the test
*/
waits(ms) {
this._waitsMillis = ms
return this
}
/**
* @param {string} header - header key
* @param {string} content - header value content
* @return {object}
* @desc Add HTTP header by key and value
*/
addHeader(header, content) {
this.current.request.headers[(header + '').toLowerCase()] = content + ''
return this
}
/**
* @param {object} headers - header object {k:v, k:v}
* @return {object}
* @desc Add group of HTTP headers together
*/
addHeaders(headers) {
Object.keys(headers).forEach(key => {
this.addHeader(key, headers[key])
})
return this
}
/**
* @param {string} key - header key to remove
* @return {object}
* @desc Remove HTTP header from outgoing request by key
*/
removeHeader(key) {
delete this.current.request.headers[(key + '').toLowerCase()]
return this
}
/**
* @param {string} user - username
* @param {string} pass - password
* @param {boolean} digest - set digest
* @return {object}
* @desc Setup HTTP basic auth
*/
auth(user, pass, digest) {
this.current.request.auth = {
sendImmediately: !digest,
user,
pass,
}
return this
}
/**
* @param {object} options object
*
* @desc Set configuration options on this object.
* inspectOnFailure: This is a really neat option that will help you figure out what is happening with your requests. Dumps request/response information to the logs.
* timeout: Sets the maximum time we'll wait for a response before failing the request
* retry: Number of times we'll try this request before returning a failure. If timeout is set, each retry uses the timeout.
* request: Options for the request module. An object containing any of these: https://github.com/request/request#requestoptions-callback
* json: Sets body to JSON representation of value and adds Content-type: application/json header. Additionally, parses the response body as JSON.
*/
config(opts) {
if ('inspectOnFailure' in opts) {
this._inspectOnFailure = opts.inspectOnFailure
}
if ('timeout' in opts) {
this._timeout = opts.timeout
}
if ('retry' in opts) {
this._attempts.maxRetries = opts.retry
}
if ('request' in opts) {
const request_options = _.cloneDeep(opts.request)
for (const request_option in request_options) {
if (request_option in request_options) {
if (request_option == 'headers') {
this.addHeaders(request_options[request_option]) //Deals with case sensitivity
} else {
this.current.request[request_option] =
request_options[request_option]
}
}
}
}
if ('json' in opts) {
this.current.request.json = opts.json //opts.json will override opts.request.json, if provided
}
return this
}
/**
* Set exception handler callback function.
*/
exceptionHandler(fn) {
if (_.isUndefined(fn)) {
return this._exceptionHandler
}
this._exceptionHandler = fn
return this
}
/**
* @return {object}
* @desc Reset Frisby global and setup options
*/
reset() {
throw Error(
"reset() has been removed from IcedFrisby v2.0+ - there's no more globalSetup(), use config() instead"
)
}
/**
* @param {array} arguments - method [uri, data, params]
* @param {string} uri - resource
* @param {object} [data] - post data
* @param {string} [param] - uri parameters
* @return {object}
* @desc _request object
*/
_request() {
const args = Array.from(arguments)
const method = args.shift()
const uri = typeof args[0] === 'string' && args.shift()
const data = typeof args[0] === 'object' && args.shift()
const params = typeof args[0] === 'object' && args.shift()
this._requestArgs = { method, uri, data, params }
// Store test runner function (request or provided mock).
this._runner = params.mock || request
return this
}
/**
* Perform GET request against resource
* @param {string} uri - resource
* @param {object} [params] - uri parameters
* @return {object}
* @desc Perform an HTTP GET request
* @example
* .get('/resource', {key: value})
*/
get(uri, params) {
return this._request.apply(this, ['GET', uri, null, params])
}
/**
* @param {string} uri - resource
* @param {object} [data] - patch data
* @param {string} [param] - uri parameters
* @desc Perform HTTP PATCH request
* @example
* .patch('/resource', {key: value}, {key: value})
*/
patch(uri, data, params) {
return this._request.apply(this, ['PATCH', uri, data, params])
}
/**
* @param {string} uri - resource
* @param {object} [data] - post data
* @param {string} [param] - uri parameters
* @return {object}
* @desc Perform HTTP POST request
* @example
* .post('/resource', {key: value}, {key: value})
*/
post(uri, data, params) {
return this._request.apply(this, ['POST', uri, data, params])
}
/**
* @param {string} uri - resource
* @param {object} [data] - put data
* @param {string} [param] - uri parameters
* @return {object}
* @desc Perform HTTP PUT request
* @example
* .put('/resource', {key: value}, {key: value})
*/
put(uri, data, params) {
return this._request.apply(this, ['PUT', uri, data, params])
}
/**
* @param {string} uri - resource
* @param {object} [data] - delete data
* @param {string} [param] - uri parameters
* @return {object}
* @desc Perform HTTP DELETE request
* @example
* .delete('/resource', {key: value}, {key: value})
*/
delete(uri, data, params) {
return this._request.apply(this, ['DELETE', uri, data, params])
}
/**
* @param {string} uri - resource (/identifier)
* @param {string} [params] - uri parameters
* @return {object}
* @desc Perform HTTP HEAD request
* @example
* .head('/resource', {key: value})
*/
head(uri, params) {
return this._request.apply(this, ['HEAD', uri, null, params])
}
/**
* @param {string} uri - resource (/identifier)
* @param {string} [params] - uri parameters
* @return {object}
* @desc Perform HTTP OPTIONS request
* @example
* .options('/resource', {key: value}, {key: value})
*/
options(uri, params) {
return this._request.apply(this, ['OPTIONS', uri, null, params])
}
_expect(fn) {
this._expects.push(fn)
return this
}
/**
* @param {string} header - header key
* @param {string} content - header value content
* @return {object}
* @desc Add HTTP header by key and value
*/
not() {
this.current.isNot = true
return this
}
/**
* @param {number} ms - Maximum response timeout in n milliseconds
* @return {object}
* @desc HTTP max response time expect helper
*/
expectMaxResponseTime(ms) {
return this._expect(() => {
chai.expect(this._response.time).to.be.lessThan(ms)
})
}
/**
* @param {number} statusCode - HTTP status code
* @return {object}
* @desc HTTP status code expect helper
*/
expectStatus(statusCode) {
return this._expect(() => {
chai.expect(this._response.status).to.equal(statusCode)
})
}
/**
* @param {string} header - header key
* @param {string} content - header value content
* @return {object}
* @desc HTTP header expect helper
*/
expectHeader(header, content, options = {}) {
const self = this
header = (header + '').toLowerCase()
options = {
allowMultipleHeaders: options.allowMultipleHeaders || false,
}
return this._expect(function () {
if (
!options.allowMultipleHeaders &&
self._response.headers[header] instanceof Array
) {
throw new Error(
"Header '" +
header +
"' present more than once in HTTP response. Pass {allowMultipleHeaders: true} in options if this is expected."
)
}
if (typeof self._response.headers[header] !== 'undefined') {
let responseHeaders = [].concat(self._response.headers[header])
if (content instanceof RegExp) {
chai
.expect(responseHeaders)
.to.include.something.that.matches(content)
} else if (typeof content === 'string') {
responseHeaders = responseHeaders.map(thisHeader =>
thisHeader.toLowerCase()
)
chai
.expect(responseHeaders)
.to.include.a.thing.that.equals(content.toLowerCase())
} else {
throw new Error(
"Content '" + content + "' is neither a string or regex"
)
}
} else {
throw new Error("Header '" + header + "' not present in HTTP response")
}
})
}
/**
* @param {string} header - header key
* @param {string} content - header value content
* @return {object}
* @desc HTTP header expect helper (using 'contains' instead of 'equals')
*/
expectHeaderContains(header, content, options = {}) {
header = (header + '').toLowerCase()
options = {
allowMultipleHeaders: options.allowMultipleHeaders || false,
}
return this._expect(() => {
if (
!options.allowMultipleHeaders &&
this._response.headers[header] instanceof Array
) {
throw new Error(
"Header '" +
header +
"' present more than once in HTTP response. Pass {allowMultipleHeaders: true} in options if this is expected."
)
}
if (typeof this._response.headers[header] !== 'undefined') {
const responseHeaders = []
.concat(this._response.headers[header])
.map(thisHeader => thisHeader.toLowerCase())
chai
.expect(responseHeaders)
.to.include.something.that.satisfies(
thisHeader =>
thisHeader.toLowerCase().includes(content.toLowerCase()),
content.toLowerCase() + ' not found in ' + responseHeaders
)
// Ugly workaround for https://github.com/chaijs/chai-things/issues/42 or something closely related
// .include.something.that.contains(textVar) has the same problem, and all values
// are checked, throwing failures when one doesn't match.
// Hence the awful use of custom messaging... Sorry.
} else {
throw new Error("Header '" + header + "' not present in HTTP response")
}
})
}
/**
* @param {string} header - header key
* @param {string} pattern - header value content regular express
* @return {object}
* @desc Alias for expectHeader
*/
expectHeaderToMatch(header, pattern) {
return this.expectHeader(header, pattern)
}
/**
* @param {string} header - header key
* @return {object}
* @desc Asserts that a header is not present in the response
*/
expectNoHeader(header) {
header = (header + '').toLowerCase()
return this._expect(() => {
chai.expect(this._response.headers).to.not.have.property(header)
})
}
/**
* @param {string} content - body content
* @return {object}
* @desc HTTP body expect helper
*/
expectBodyContains(content) {
return this._expect(() => {
chai.expect(this._response.body).to.contain(content)
})
}
/**
* @param {array} arguments - joi tree, path, jsonTest
* @return {object}
* @desc Helper to check parse HTTP response body as JSON and check key types
*/
expectJSONTypes(/* [tree], jsonTest */) {
const args = Array.from(arguments)
const path = typeof args[0] === 'string' && args.shift()
const jsonTest = typeof args[0] === 'object' && args.shift()
return this._expect(() => {
pm.matchJSONTypes({
jsonBody: _jsonParse(this._response.body),
jsonTest: jsonTest,
isNot: this.current.isNot,
path: path,
})
})
}
/**
* @param {array} jsonTest - [path, jsonTest]
* @return {object}
* @desc Helper to check JSON response body exactly matches a provided object
*/
expectJSON(jsonTest) {
const args = Array.from(arguments)
const path = typeof args[0] === 'string' && args.shift()
jsonTest = typeof args[0] === 'object' && args.shift()
return this._expect(() => {
pm.matchJSON({
jsonBody: _jsonParse(this._response.body),
jsonTest,
isNot: this.current.isNot,
path,
})
})
}
/**
* @param {array} jsonTest - [path, jsonTest]
* @return {object}
* @desc Helper to check JSON response contains a provided object
*/
expectContainsJSON(jsonTest) {
const args = Array.from(arguments)
const path = typeof args[0] === 'string' && args.shift()
jsonTest = typeof args[0] === 'object' && args.shift()
return this._expect(() => {
pm.matchContainsJSON({
jsonBody: _jsonParse(this._response.body),
jsonTest,
isNot: this.current.isNot,
path,
})
})
}
/**
* @param {array} expectedLength - [path, expectedLength]
* @return {object}
* @desc Helper to check response body as JSON and check array or object length
*/
expectJSONLength(expectedLength) {
const args = Array.from(arguments)
const path = _.isString(args[0]) && args.shift() // optional 1st parameter
expectedLength =
(_.isNumber(args[0]) || _.isString(args[0])) && args.shift() // 1st or 2nd parameter
let lengthSegments = null
// if expectedLength is a string, we have to parse out the sign
if (!_.isNumber(expectedLength)) {
const sign = /\D+/.exec(expectedLength)
lengthSegments = {
count: parseInt(/\d+/.exec(expectedLength), 10),
sign: sign ? sign[0].trim() : null, // extract the sign, e.g. <, <=, >, >= and trim out whitespace
}
} else {
lengthSegments = {
count: expectedLength,
sign: null,
}
}
return this._expect(() => {
pm.matchJSONLength({
jsonBody: _jsonParse(this._response.body),
jsonTest: lengthSegments, // we aren't testing any JSON here, just use this to pass in the length segments
isNot: this.current.isNot,
path,
})
})
}
/**
* @param {inspectCallback} cb - callback
* @return {object}
* @desc inspection of data after request is made but before test is completed
*/
inspect(cb) {
// This function uses both `self` and `this`. Are they different? Hmm.
const self = this
if (!cb) {
return self
}
// Node invokes inspect() when printing formatting objects. Guess if that's
// happening based on the arguments passed, and delgate back to inspect,
// disabling custom inspection.
// https://nodejs.org/api/util.html#util_custom_inspection_functions_on_objects
if (typeof cb !== 'function') {
return util.inspect(self, { customInspect: false })
}
this._inspects.push(function () {
cb.call(
this,
self._response.error,
self.currentRequestFinished.req,
self.currentRequestFinished.res,
self._response.body,
self._response.headers
)
})
return this
}
/**
* @param {string} message - message to print before the inspection
* @return {object}
* @desc Debugging helper to inspect the HTTP request
*/
inspectRequest(message) {
this.inspect(function (err, req, res, body) {
if (message) {
console.log(message)
}
console.log(req)
})
return this
}
/**
* @param {string} message - message to print before the inspection
* @return {object}
* @desc Debugging helper to inspect the HTTP response
*/
inspectResponse(message) {
this.inspect(function (err, req, res, body) {
if (message) {
console.log(message)
}
console.log(res)
})
return this
}
/**
* @param {string} message - message to print before the inspection
* @return {object}
* @desc Debugging helper to inspect the HTTP headers
*/
inspectHeaders(message) {
this.inspect(function (err, req, res, body) {
if (message) {
console.log(message)
}
console.log(res.headers)
})
return this
}
/**
* @param {string} message - message to print before the inspection
* @return {object}
* @desc Debugging helper to inspect the HTTP response body content
*/
inspectBody(message) {
this.inspect(function (err, req, res, body) {
if (message) {
console.log(message)
}
console.log(body)
})
return this
}
/**
* @param {string} message - message to print before the inspection
* @return {object}
* @desc Debugging helper to inspect the JSON response body content
*/
inspectJSON(message) {
this.inspect(function (err, req, res, body) {
if (message) {
console.log(message)
}
console.log(util.inspect(_jsonParse(body), false, 10, true))
})
return this
}
/**
* @param {string} message - message to print before the inspection
* @return {object}
* @desc Debugging helper to inspect the HTTP response code
*/
inspectStatus(message) {
this.inspect(function (err, req, res, body) {
if (message) {
console.log(message)
}
console.log(res.statusCode)
})
return this
}
_performInspections() {
this._inspects.forEach(fn => fn())
}
/**
* @param {afterCallback} cb - callback
* @return {object}
* @desc callback function to run before the request is made
*/
before(cb) {
if (!_.isFunction(cb)) {
throw new Error(
'Expected Function object in before(), but got ' + typeof cb
)
}
this._hooks.before.push(cb)
return this
}
/**
* @param {afterCallback} cb - callback
* @return {object}
* @desc callback function to run after test is completed
*/
after(cb) {
if (!_.isFunction(cb)) {
throw new Error(
'Expected Function object in after(), but got ' + typeof cb
)
}
if (cb.length > 4) {
// assume it has a callback function argument
this._hooks.after.push(done => {
cb.call(
this,
this._response.error,
this.currentRequestFinished.res,
this._response.body,
this._response.headers,
done
)
})
} else {
this._hooks.after.push(() => {
cb.call(
this,
this._response.error,
this.currentRequestFinished.res,
this._response.body,
this._response.headers
)
})
}
return this
}
/**
* @param {afterJSONCallback} cb - callback
* @return {object}
* @desc Callback function to run after test is completed,
* helper to convert response body to JSON
* @example
* .afterJSON(function(json) {
* // previous test JSON response
* let id = json.id
* frisby.create(msg)
* .get('/item' + id)
* .toss()
* })
*/
afterJSON(cb) {
this._hooks.after.push(function () {
const responseHeaders = _jsonParse(this._response.headers)
const bodyJSON = _jsonParse(this._response.body)
cb.call(this, bodyJSON, responseHeaders)
})
return this
}
/**
* Register a hook to run after a test runs, regardless of whether it
* succeeded or failed.
* @param {finallyCallback} cb - callback
* @return {object}
*/
finally(cb) {
if (!_.isFunction(cb)) {
throw new Error(
'Expected Function object in finally(), but got ' + typeof cb
)
}
this._hooks.finally.push(cb)
return this
}
async _runHooks(hooks) {
return new Promise((resolve, reject) => {
let invokationIndex = 0
// naiive implementation of async callback support:
const invokeNextHook = () => {
if (invokationIndex === hooks.length) {
resolve()
} else {
const nextHook = hooks[invokationIndex++]
if (nextHook.length) {
// assume it has a callback function argument
try {
nextHook.call(this, invokeNextHook)
} catch (e) {
if (false === this._exceptionHandler) {
this._failures.push(e)
//Fishbowler 25-6-2018: No unit tests for this line - currently unreachable.
return reject(e)
} else {
this._exceptionHandler(e)
setImmediate(invokeNextHook)
}
}
} else {