diff --git a/lib/match_body.js b/lib/match_body.js index 436b7b53a..3d568ecbd 100644 --- a/lib/match_body.js +++ b/lib/match_body.js @@ -63,10 +63,11 @@ module.exports = function matchBody(options, spec, body) { function mapValues(object, cb) { const keys = Object.keys(object) + const clonedObject = { ...object } for (const key of keys) { - object[key] = cb(object[key], key, object) + clonedObject[key] = cb(clonedObject[key], key, clonedObject) } - return object + return clonedObject } /** diff --git a/tests/got/test_reply_body.js b/tests/got/test_reply_body.js index 71f44ff7c..ebedb07af 100644 --- a/tests/got/test_reply_body.js +++ b/tests/got/test_reply_body.js @@ -115,6 +115,23 @@ describe('`reply()` body', () => { expect(body).to.be.a('string').and.equal('') scope.done() }) + + it('does not modify the object used for response', async () => { + const patchBody = { number: 1234 } + const form = new FormData() + form.append('number', 1234) + + const scope = nock('http://example.test') + .patch('/', patchBody) + .reply(200, patchBody) + + await got.patch('http://example.test/', { + form, + }) + + expect(patchBody.number).to.be.a('number').and.equal(1234) + scope.done() + }) }) describe('`reply()` status code', () => { diff --git a/tests/test_common.js b/tests/test_common.js index f91ddb474..68d8922dc 100644 --- a/tests/test_common.js +++ b/tests/test_common.js @@ -71,6 +71,18 @@ describe('Body Match', () => { const result = matchBody({}, { number: 1 }, '{"number": "1"}') expect(result).to.equal(false) }) + + it('should not modify the original spec object', () => { + const spec = { number: 1 } + matchBody( + { + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + }, + spec, + '', + ) + expect(spec).to.deep.equal({ number: 1 }) + }) }) })