Skip to content

Commit

Permalink
fix(recorder): escape single quotes in path of default output (#2137)
Browse files Browse the repository at this point in the history
Because the default output of the recorder uses single quotes, any such
quotes in the path would generate invalid Javascript.
  • Loading branch information
mastermatt committed Jan 30, 2021
1 parent dc04694 commit 0f7b52e
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
4 changes: 4 additions & 0 deletions lib/recorder.js
Expand Up @@ -110,6 +110,10 @@ function generateRequestAndResponse({
const queryStr = req.path.slice(queryIndex + 1)
queryObj = querystring.parse(queryStr)
}

// Escape any single quotes in the path as the output uses them
path = path.replace(/'/g, `\\'`)

// Always encode the query parameters when recording.
const encodedQueryObj = {}
for (const key in queryObj) {
Expand Down
22 changes: 22 additions & 0 deletions tests/test_recorder.js
Expand Up @@ -13,6 +13,8 @@ const servers = require('./servers')

require('./setup')

// TODO: the guts of this file should be wrapped in a `describe`.
// These before and afters run for every test in the repo under Mocha.
let globalCount
beforeEach(() => {
globalCount = Object.keys(global).length
Expand Down Expand Up @@ -1148,6 +1150,26 @@ it('removes query params from the path and puts them in query()', done => {
})
})

// https://github.com/nock/nock/issues/2136
it('escapes single quotes in the path', async () => {
const { origin } = await servers.startHttpServer((request, response) => {
response.writeHead(200)
response.end()
})

nock.restore()
nock.recorder.clear()
expect(nock.recorder.play()).to.be.empty()

nock.recorder.rec(true)

await got(`${origin}/foo'bar'baz`)

const recorded = nock.recorder.play()
expect(recorded).to.have.lengthOf(1)
expect(recorded[0]).to.be.a('string').and.include(`.get('/foo\\'bar\\'baz')`)
})

it('respects http.request() consumers', done => {
const requestListener = (req, res) => {
res.write('foo')
Expand Down

0 comments on commit 0f7b52e

Please sign in to comment.