Skip to content

Commit

Permalink
fix: allowMocked when using a callback for the path (#1877)
Browse files Browse the repository at this point in the history
* fix: allowMocked when using a callback for the path

When an Interceptor was created with a comparator for the path, the
`matchOrigin` function was comparing the string equivalent of the function
instead of evaluating it.

I'm not a fan of the fact that the function `matchOrigin` is comparing the
pathname, but that's a refactor for another day.

Fixes: #1867
  • Loading branch information
mastermatt committed Feb 10, 2020
1 parent a56a209 commit 9fdeeca
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
7 changes: 6 additions & 1 deletion lib/interceptor.js
Expand Up @@ -355,6 +355,7 @@ module.exports = class Interceptor {
* match the provided options.
*/
matchOrigin(options) {
const isPathFn = typeof this.path === 'function'
const isRegex = this.path instanceof RegExp
const isRegexBasePath = this.scope.basePath instanceof RegExp

Expand All @@ -370,9 +371,13 @@ module.exports = class Interceptor {
if (this.scope.transformPathFunction) {
path = this.scope.transformPathFunction(path)
}
const comparisonKey = isRegex ? this.__nock_scopeKey : this._key
const comparisonKey = isPathFn || isRegex ? this.__nock_scopeKey : this._key
const matchKey = `${method} ${proto}://${options.host}${path}`

if (isPathFn) {
return !!(matchKey.match(comparisonKey) && this.path(path))
}

if (isRegex && !isRegexBasePath) {
return !!matchKey.match(comparisonKey) && this.path.test(path)
}
Expand Down
13 changes: 13 additions & 0 deletions tests/test_allow_unmocked.js
@@ -1,6 +1,7 @@
'use strict'

const http = require('http')
const { expect } = require('chai')
const url = require('url')
const mikealRequest = require('request')
const { test } = require('tap')
Expand Down Expand Up @@ -233,6 +234,18 @@ test('match hostname using regexp with allowUnmocked (issue-1076)', t => {
})
})

// https://github.com/nock/nock/issues/1867
test('match path using callback with allowUnmocked', async t => {
const scope = nock('http://example.test', { allowUnmocked: true })
.get(uri => uri.endsWith('bar'))
.reply()

const { statusCode } = await got('http://example.test/foo/bar')
expect(statusCode).to.equal(200)

scope.done()
})

// https://github.com/nock/nock/issues/835
test('match multiple paths to domain using regexp with allowUnmocked', async t => {
const server = http.createServer((request, response) => {
Expand Down

0 comments on commit 9fdeeca

Please sign in to comment.