From 0f7b52e044eaf139c0a97613ef9035bb4dd13b80 Mon Sep 17 00:00:00 2001 From: "Matt R. Wilson" Date: Fri, 29 Jan 2021 20:12:47 -0700 Subject: [PATCH] fix(recorder): escape single quotes in path of default output (#2137) Because the default output of the recorder uses single quotes, any such quotes in the path would generate invalid Javascript. --- lib/recorder.js | 4 ++++ tests/test_recorder.js | 22 ++++++++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/lib/recorder.js b/lib/recorder.js index 7c1c625d1..6903d8d20 100644 --- a/lib/recorder.js +++ b/lib/recorder.js @@ -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) { diff --git a/tests/test_recorder.js b/tests/test_recorder.js index 6c4831267..3a91a08aa 100644 --- a/tests/test_recorder.js +++ b/tests/test_recorder.js @@ -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 @@ -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')