UNPKG

17.7 kBJavaScriptView Raw
1'use strict'
2
3const debug = require('debug')('nock.interceptor')
4const stringify = require('json-stringify-safe')
5const _ = require('lodash')
6const querystring = require('querystring')
7const { URL, URLSearchParams } = require('url')
8
9const common = require('./common')
10const { remove } = require('./intercept')
11const matchBody = require('./match_body')
12
13let fs
14try {
15 fs = require('fs')
16} catch (err) {
17 // do nothing, we're in the browser
18}
19
20module.exports = class Interceptor {
21 /**
22 *
23 * Valid argument types for `uri`:
24 * - A string used for strict comparisons with pathname.
25 * The search portion of the URI may also be postfixed, in which case the search params
26 * are striped and added via the `query` method.
27 * - A RegExp instance that tests against only the pathname of requests.
28 * - A synchronous function bound to this Interceptor instance. It's provided the pathname
29 * of requests and must return a boolean denoting if the request is considered a match.
30 */
31 constructor(scope, uri, method, requestBody, interceptorOptions) {
32 const uriIsStr = typeof uri === 'string'
33 // Check for leading slash. Uri can be either a string or a regexp, but
34 // When enabled filteringScope ignores the passed URL entirely so we skip validation.
35
36 if (
37 !scope.scopeOptions.filteringScope &&
38 uriIsStr &&
39 !uri.startsWith('/') &&
40 !uri.startsWith('*')
41 ) {
42 throw Error(
43 `Non-wildcard URL path strings must begin with a slash (otherwise they won't match anything) (got: ${uri})`
44 )
45 }
46
47 if (!method) {
48 throw new Error(
49 'The "method" parameter is required for an intercept call.'
50 )
51 }
52
53 this.scope = scope
54 this.interceptorMatchHeaders = []
55 this.method = method.toUpperCase()
56 this.uri = uri
57 this._key = `${this.method} ${scope.basePath}${scope.basePathname}${
58 uriIsStr ? '' : '/'
59 }${uri}`
60 this.basePath = this.scope.basePath
61 this.path = uriIsStr ? scope.basePathname + uri : uri
62 this.queries = null
63
64 this.options = interceptorOptions || {}
65 this.counter = 1
66 this._requestBody = requestBody
67
68 // We use lower-case header field names throughout Nock.
69 this.reqheaders = common.headersFieldNamesToLowerCase(
70 scope.scopeOptions.reqheaders || {}
71 )
72 this.badheaders = common.headersFieldsArrayToLowerCase(
73 scope.scopeOptions.badheaders || []
74 )
75
76 this.delayInMs = 0
77 this.delayConnectionInMs = 0
78
79 this.optional = false
80
81 // strip off literal query parameters if they were provided as part of the URI
82 if (uriIsStr && uri.includes('?')) {
83 // localhost is a dummy value because the URL constructor errors for only relative inputs
84 const parsedURL = new URL(this.path, 'http://localhost')
85 this.path = parsedURL.pathname
86 this.query(parsedURL.searchParams)
87 this._key = `${this.method} ${scope.basePath}${this.path}`
88 }
89 }
90
91 optionally(flag = true) {
92 // The default behaviour of optionally() with no arguments is to make the mock optional.
93 if (typeof flag !== 'boolean') {
94 throw new Error('Invalid arguments: argument should be a boolean')
95 }
96
97 this.optional = flag
98
99 return this
100 }
101
102 replyWithError(errorMessage) {
103 this.errorMessage = errorMessage
104
105 _.defaults(this.options, this.scope.scopeOptions)
106
107 this.scope.add(this._key, this)
108 return this.scope
109 }
110
111 reply(statusCode, body, rawHeaders) {
112 // support the format of only passing in a callback
113 if (typeof statusCode === 'function') {
114 if (arguments.length > 1) {
115 // It's not very Javascript-y to throw an error for extra args to a function, but because
116 // of legacy behavior, this error was added to reduce confusion for those migrating.
117 throw Error(
118 'Invalid arguments. When providing a function for the first argument, .reply does not accept other arguments.'
119 )
120 }
121 this.statusCode = null
122 this.fullReplyFunction = statusCode
123 } else {
124 if (statusCode !== undefined && !Number.isInteger(statusCode)) {
125 throw new Error(`Invalid ${typeof statusCode} value for status code`)
126 }
127
128 this.statusCode = statusCode || 200
129 if (typeof body === 'function') {
130 this.replyFunction = body
131 body = null
132 }
133 }
134
135 _.defaults(this.options, this.scope.scopeOptions)
136
137 this.rawHeaders = common.headersInputToRawArray(rawHeaders)
138
139 if (this.scope.date) {
140 // https://tools.ietf.org/html/rfc7231#section-7.1.1.2
141 this.rawHeaders.push('Date', this.scope.date.toUTCString())
142 }
143
144 // Prepare the headers temporarily so we can make best guesses about content-encoding and content-type
145 // below as well as while the response is being processed in RequestOverrider.end().
146 // Including all the default headers is safe for our purposes because of the specific headers we introspect.
147 // A more thoughtful process is used to merge the default headers when the response headers are finally computed.
148 this.headers = common.headersArrayToObject(
149 this.rawHeaders.concat(this.scope._defaultReplyHeaders)
150 )
151
152 // If the content is not encoded we may need to transform the response body.
153 // Otherwise we leave it as it is.
154 if (
155 body &&
156 typeof body !== 'string' &&
157 !Buffer.isBuffer(body) &&
158 !common.isStream(body) &&
159 !common.isContentEncoded(this.headers)
160 ) {
161 try {
162 body = stringify(body)
163 } catch (err) {
164 throw new Error('Error encoding response body into JSON')
165 }
166
167 if (!this.headers['content-type']) {
168 // https://tools.ietf.org/html/rfc7231#section-3.1.1.5
169 this.rawHeaders.push('Content-Type', 'application/json')
170 }
171
172 if (this.scope.contentLen) {
173 // https://tools.ietf.org/html/rfc7230#section-3.3.2
174 this.rawHeaders.push('Content-Length', body.length)
175 }
176 }
177
178 debug('reply.headers:', this.headers)
179 debug('reply.rawHeaders:', this.rawHeaders)
180
181 this.body = body
182
183 this.scope.add(this._key, this)
184 return this.scope
185 }
186
187 replyWithFile(statusCode, filePath, headers) {
188 if (!fs) {
189 throw new Error('No fs')
190 }
191 const readStream = fs.createReadStream(filePath)
192 readStream.pause()
193 this.filePath = filePath
194 return this.reply(statusCode, readStream, headers)
195 }
196
197 // Also match request headers
198 // https://github.com/nock/nock/issues/163
199 reqheaderMatches(options, key) {
200 const reqHeader = this.reqheaders[key]
201 let header = options.headers[key]
202
203 // https://github.com/nock/nock/issues/399
204 // https://github.com/nock/nock/issues/822
205 if (header && typeof header !== 'string' && header.toString) {
206 header = header.toString()
207 }
208
209 // We skip 'host' header comparison unless it's available in both mock and
210 // actual request. This because 'host' may get inserted by Nock itself and
211 // then get recorded. NOTE: We use lower-case header field names throughout
212 // Nock. See https://github.com/nock/nock/pull/196.
213 if (key === 'host' && (header === undefined || reqHeader === undefined)) {
214 return true
215 }
216
217 if (reqHeader !== undefined && header !== undefined) {
218 if (typeof reqHeader === 'function') {
219 return reqHeader(header)
220 } else if (common.matchStringOrRegexp(header, reqHeader)) {
221 return true
222 }
223 }
224
225 debug("request header field doesn't match:", key, header, reqHeader)
226 return false
227 }
228
229 match(req, options, body) {
230 if (debug.enabled) {
231 debug('match %s, body = %s', stringify(options), stringify(body))
232 }
233
234 const method = (options.method || 'GET').toUpperCase()
235 let { path = '/' } = options
236 let matches
237 let matchKey
238 const { proto } = options
239
240 if (this.method !== method) {
241 debug(
242 `Method did not match. Request ${method} Interceptor ${this.method}`
243 )
244 return false
245 }
246
247 if (this.scope.transformPathFunction) {
248 path = this.scope.transformPathFunction(path)
249 }
250
251 const requestMatchesFilter = ({ name, value: predicate }) => {
252 const headerValue = req.getHeader(name)
253 if (typeof predicate === 'function') {
254 return predicate(headerValue)
255 } else {
256 return common.matchStringOrRegexp(headerValue, predicate)
257 }
258 }
259
260 if (
261 !this.scope.matchHeaders.every(requestMatchesFilter) ||
262 !this.interceptorMatchHeaders.every(requestMatchesFilter)
263 ) {
264 this.scope.logger("headers don't match")
265 return false
266 }
267
268 const reqHeadersMatch = Object.keys(this.reqheaders).every(key =>
269 this.reqheaderMatches(options, key)
270 )
271
272 if (!reqHeadersMatch) {
273 return false
274 }
275
276 if (
277 this.scope.scopeOptions.conditionally &&
278 !this.scope.scopeOptions.conditionally()
279 ) {
280 return false
281 }
282
283 const reqContainsBadHeaders = this.badheaders.some(
284 header => header in options.headers
285 )
286
287 if (reqContainsBadHeaders) {
288 return false
289 }
290
291 // Match query strings when using query()
292 if (this.queries === null) {
293 debug('query matching skipped')
294 } else {
295 // can't rely on pathname or search being in the options, but path has a default
296 const [pathname, search] = path.split('?')
297 const matchQueries = this.matchQuery({ search })
298
299 debug(matchQueries ? 'query matching succeeded' : 'query matching failed')
300
301 if (!matchQueries) {
302 return false
303 }
304
305 // If the query string was explicitly checked then subsequent checks against
306 // the path using a callback or regexp only validate the pathname.
307 path = pathname
308 }
309
310 // If we have a filtered scope then we use it instead reconstructing the
311 // scope from the request options (proto, host and port) as these two won't
312 // necessarily match and we have to remove the scope that was matched (vs.
313 // that was defined).
314 if (this.__nock_filteredScope) {
315 matchKey = this.__nock_filteredScope
316 } else {
317 matchKey = common.normalizeOrigin(proto, options.host, options.port)
318 }
319
320 if (typeof this.uri === 'function') {
321 matches =
322 common.matchStringOrRegexp(matchKey, this.basePath) &&
323 // This is a false positive, as `uri` is not bound to `this`.
324 // eslint-disable-next-line no-useless-call
325 this.uri.call(this, path)
326 } else {
327 matches =
328 common.matchStringOrRegexp(matchKey, this.basePath) &&
329 common.matchStringOrRegexp(path, this.path)
330 }
331
332 this.scope.logger(`matching ${matchKey}${path} to ${this._key}: ${matches}`)
333
334 if (matches && this._requestBody !== undefined) {
335 if (this.scope.transformRequestBodyFunction) {
336 body = this.scope.transformRequestBodyFunction(body, this._requestBody)
337 }
338
339 matches = matchBody(options, this._requestBody, body)
340 if (!matches) {
341 this.scope.logger(
342 "bodies don't match: \n",
343 this._requestBody,
344 '\n',
345 body
346 )
347 }
348 }
349
350 return matches
351 }
352
353 /**
354 * Return true when the interceptor's method, protocol, host, port, and path
355 * match the provided options.
356 */
357 matchOrigin(options) {
358 const isRegex = this.path instanceof RegExp
359 const isRegexBasePath = this.scope.basePath instanceof RegExp
360
361 const method = (options.method || 'GET').toUpperCase()
362 let { path } = options
363 const { proto } = options
364
365 // NOTE: Do not split off the query params as the regex could use them
366 if (!isRegex) {
367 path = path ? path.split('?')[0] : ''
368 }
369
370 if (this.scope.transformPathFunction) {
371 path = this.scope.transformPathFunction(path)
372 }
373 const comparisonKey = isRegex ? this.__nock_scopeKey : this._key
374 const matchKey = `${method} ${proto}://${options.host}${path}`
375
376 if (isRegex && !isRegexBasePath) {
377 return !!matchKey.match(comparisonKey) && this.path.test(path)
378 }
379
380 if (isRegexBasePath) {
381 return this.scope.basePath.test(matchKey) && !!path.match(this.path)
382 }
383
384 return comparisonKey === matchKey
385 }
386
387 matchHostName(options) {
388 return options.hostname === this.scope.urlParts.hostname
389 }
390
391 matchQuery(options) {
392 if (this.queries === true) {
393 return true
394 }
395
396 const reqQueries = querystring.parse(options.search)
397 debug('Interceptor queries: %j', this.queries)
398 debug(' Request queries: %j', reqQueries)
399
400 if (typeof this.queries === 'function') {
401 return this.queries(reqQueries)
402 }
403
404 return common.dataEqual(this.queries, reqQueries)
405 }
406
407 filteringPath(...args) {
408 this.scope.filteringPath(...args)
409 return this
410 }
411
412 // TODO filtering by path is valid on the intercept level, but not filtering
413 // by request body?
414
415 markConsumed() {
416 this.interceptionCounter++
417
418 remove(this)
419
420 if ((this.scope.shouldPersist() || this.counter > 0) && this.filePath) {
421 this.body = fs.createReadStream(this.filePath)
422 this.body.pause()
423 }
424
425 if (!this.scope.shouldPersist() && this.counter < 1) {
426 this.scope.remove(this._key, this)
427 }
428 }
429
430 matchHeader(name, value) {
431 this.interceptorMatchHeaders.push({ name, value })
432 return this
433 }
434
435 basicAuth({ user, pass = '' }) {
436 const encoded = Buffer.from(`${user}:${pass}`).toString('base64')
437 this.matchHeader('authorization', `Basic ${encoded}`)
438 return this
439 }
440
441 /**
442 * Set query strings for the interceptor
443 * @name query
444 * @param queries Object of query string name,values (accepts regexp values)
445 * @public
446 * @example
447 * // Will match 'http://zombo.com/?q=t'
448 * nock('http://zombo.com').get('/').query({q: 't'});
449 */
450 query(queries) {
451 if (this.queries !== null) {
452 throw Error(`Query parameters have already been defined`)
453 }
454
455 // Allow all query strings to match this route
456 if (queries === true) {
457 this.queries = queries
458 return this
459 }
460
461 if (typeof queries === 'function') {
462 this.queries = queries
463 return this
464 }
465
466 let strFormattingFn
467 if (this.scope.scopeOptions.encodedQueryParams) {
468 strFormattingFn = common.percentDecode
469 }
470
471 if (queries instanceof URLSearchParams) {
472 // Normalize the data into the shape that is matched against.
473 // Duplicate keys are handled by combining the values into an array.
474 queries = querystring.parse(queries.toString())
475 } else if (!_.isPlainObject(queries)) {
476 throw Error(`Argument Error: ${queries}`)
477 }
478
479 this.queries = {}
480 for (const [key, value] of Object.entries(queries)) {
481 const formatted = common.formatQueryValue(key, value, strFormattingFn)
482 const [formattedKey, formattedValue] = formatted
483 this.queries[formattedKey] = formattedValue
484 }
485
486 return this
487 }
488
489 /**
490 * Set number of times will repeat the interceptor
491 * @name times
492 * @param newCounter Number of times to repeat (should be > 0)
493 * @public
494 * @example
495 * // Will repeat mock 5 times for same king of request
496 * nock('http://zombo.com).get('/').times(5).reply(200, 'Ok');
497 */
498 times(newCounter) {
499 if (newCounter < 1) {
500 return this
501 }
502
503 this.counter = newCounter
504
505 return this
506 }
507
508 /**
509 * An sugar syntax for times(1)
510 * @name once
511 * @see {@link times}
512 * @public
513 * @example
514 * nock('http://zombo.com).get('/').once().reply(200, 'Ok');
515 */
516 once() {
517 return this.times(1)
518 }
519
520 /**
521 * An sugar syntax for times(2)
522 * @name twice
523 * @see {@link times}
524 * @public
525 * @example
526 * nock('http://zombo.com).get('/').twice().reply(200, 'Ok');
527 */
528 twice() {
529 return this.times(2)
530 }
531
532 /**
533 * An sugar syntax for times(3).
534 * @name thrice
535 * @see {@link times}
536 * @public
537 * @example
538 * nock('http://zombo.com).get('/').thrice().reply(200, 'Ok');
539 */
540 thrice() {
541 return this.times(3)
542 }
543
544 /**
545 * Delay the response by a certain number of ms.
546 *
547 * @param {(integer|object)} opts - Number of milliseconds to wait, or an object
548 * @param {integer} [opts.head] - Number of milliseconds to wait before response is sent
549 * @param {integer} [opts.body] - Number of milliseconds to wait before response body is sent
550 * @return {Interceptor} - the current interceptor for chaining
551 */
552 delay(opts) {
553 let headDelay
554 let bodyDelay
555 if (_.isNumber(opts)) {
556 headDelay = opts
557 bodyDelay = 0
558 } else if (typeof opts === 'object') {
559 headDelay = opts.head || 0
560 bodyDelay = opts.body || 0
561 } else {
562 throw new Error(`Unexpected input opts ${opts}`)
563 }
564
565 return this.delayConnection(headDelay).delayBody(bodyDelay)
566 }
567
568 /**
569 * Delay the response body by a certain number of ms.
570 *
571 * @param {integer} ms - Number of milliseconds to wait before response is sent
572 * @return {Interceptor} - the current interceptor for chaining
573 */
574 delayBody(ms) {
575 this.delayInMs += ms
576 return this
577 }
578
579 /**
580 * Delay the connection by a certain number of ms.
581 *
582 * @param {integer} ms - Number of milliseconds to wait
583 * @return {Interceptor} - the current interceptor for chaining
584 */
585 delayConnection(ms) {
586 this.delayConnectionInMs += ms
587 return this
588 }
589
590 /**
591 * @private
592 * @returns {number}
593 */
594 getTotalDelay() {
595 return this.delayInMs + this.delayConnectionInMs
596 }
597
598 /**
599 * Make the socket idle for a certain number of ms (simulated).
600 *
601 * @param {integer} ms - Number of milliseconds to wait
602 * @return {Interceptor} - the current interceptor for chaining
603 */
604 socketDelay(ms) {
605 this.socketDelayInMs = ms
606 return this
607 }
608}