Skip to content

Commit

Permalink
feat: Throw errors for URL paths without leading slashes, which will …
Browse files Browse the repository at this point in the history
…never match (#1744)

Fix #1730
  • Loading branch information
TLPcoder authored and paulmelnikow committed Oct 22, 2019
1 parent 7a568dd commit b7f9f13
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 5 deletions.
12 changes: 9 additions & 3 deletions lib/interceptor.js
Expand Up @@ -31,8 +31,14 @@ module.exports = class Interceptor {
constructor(scope, uri, method, requestBody, interceptorOptions) {
const uriIsStr = typeof uri === 'string'
// Check for leading slash. Uri can be either a string or a regexp, but
// we only need to check strings.
if (uriIsStr && /^[^/*]/.test(uri)) {
// When enabled filteringScope ignores the passed URL entirely so we skip validation.

if (
!scope.scopeOptions.filteringScope &&
uriIsStr &&
!uri.startsWith('/') &&
!uri.startsWith('*')
) {
throw Error(
`Non-wildcard URL path strings must begin with a slash (otherwise they won't match anything) (got: ${uri})`
)
Expand Down Expand Up @@ -224,7 +230,7 @@ module.exports = class Interceptor {
}

const method = (options.method || 'GET').toUpperCase()
let { path = '' } = options
let { path = '/' } = options
let matches
let matchKey
const { proto } = options
Expand Down
26 changes: 24 additions & 2 deletions tests/test_intercept.js
Expand Up @@ -1300,7 +1300,7 @@ test('match domain and path using regexp', t => {
// https://github.com/nock/nock/issues/1003
test('correctly parse request without specified path', t => {
const scope1 = nock('https://example.test')
.get('')
.get('/')
.reply(200)

https
Expand All @@ -1317,7 +1317,7 @@ test('correctly parse request without specified path', t => {

test('data is sent with flushHeaders', t => {
const scope1 = nock('https://example.test')
.get('')
.get('/')
.reply(200, 'this is data')

https
Expand All @@ -1334,6 +1334,28 @@ test('data is sent with flushHeaders', t => {
.flushHeaders()
})

// https://github.com/nock/nock/issues/1730
test('URL path without leading slash throws expected error', t => {
t.throws(() => nock('http://example.test').get(''), {
message:
"Non-wildcard URL path strings must begin with a slash (otherwise they won't match anything) (got: )",
})

t.end()
})

test('wildcard param URL should not throw error', t => {
nock('http://example.test').get('*')

t.end()
})

test('with filteringScope, URL path without leading slash does not throw error', t => {
nock('http://example.test', { filteringScope: () => {} }).get('')

t.end()
})

test('no new keys were added to the global namespace', t => {
const leaks = Object.keys(global).filter(
key => !acceptableGlobalKeys.has(key)
Expand Down

0 comments on commit b7f9f13

Please sign in to comment.