Skip to content

Commit

Permalink
fix(intercept): handle global flags during regexp matching
Browse files Browse the repository at this point in the history
When matching via a regexp instance, consistently test the entire target
string.
Sets the `lastIndex` to zero for cases where the `global` flag is set
and the
regexp instance has been tested previously.

fixes: #2134
  • Loading branch information
mastermatt committed Jan 19, 2021
1 parent ad7e481 commit ea2194c
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 3 deletions.
9 changes: 6 additions & 3 deletions lib/common.js
Expand Up @@ -416,9 +416,12 @@ function matchStringOrRegexp(target, pattern) {
const targetStr =
target === undefined || target === null ? '' : String(target)

return pattern instanceof RegExp
? pattern.test(targetStr)
: targetStr === String(pattern)
if (pattern instanceof RegExp) {
// if the regexp happens to have a global flag, we want to ensure we test the entire target
pattern.lastIndex = 0
return pattern.test(targetStr)
}
return targetStr === String(pattern)
}

/**
Expand Down
9 changes: 9 additions & 0 deletions tests/test_intercept.js
Expand Up @@ -884,6 +884,15 @@ test('match path using regexp', async t => {
expect(body).to.equal('Match regex')
})

// https://github.com/nock/nock/issues/2134
test('match path using regexp with global flag', async t => {
nock('http://example.test').get(/foo/g).reply(200, 'Match regex')

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

test('match path using function', async t => {
const path = '/match/uri/function'
const urlFunction = uri => uri === path
Expand Down

0 comments on commit ea2194c

Please sign in to comment.