UNPKG

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