From 9fdeeca7009ba8dc1b4f83b36030527f011ab665 Mon Sep 17 00:00:00 2001 From: "Matt R. Wilson" Date: Sun, 9 Feb 2020 21:41:36 -0700 Subject: [PATCH] fix: allowMocked when using a callback for the path (#1877) * 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 --- lib/interceptor.js | 7 ++++++- tests/test_allow_unmocked.js | 13 +++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/lib/interceptor.js b/lib/interceptor.js index e1a71b5ed..0bcc17125 100644 --- a/lib/interceptor.js +++ b/lib/interceptor.js @@ -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 @@ -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) } diff --git a/tests/test_allow_unmocked.js b/tests/test_allow_unmocked.js index 496d7f3f9..967eeda9e 100644 --- a/tests/test_allow_unmocked.js +++ b/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') @@ -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) => {