Skip to content

Commit

Permalink
fix: mapValues should not update the object in place (#2737)
Browse files Browse the repository at this point in the history
* fix:mapValues should not modify object in place

* test:add tests to ensure objects are not modified
  • Loading branch information
pranaygp committed Apr 20, 2024
1 parent de560ec commit b37c57f
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 2 deletions.
5 changes: 3 additions & 2 deletions lib/match_body.js
Expand Up @@ -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
}

/**
Expand Down
17 changes: 17 additions & 0 deletions tests/got/test_reply_body.js
Expand Up @@ -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', () => {
Expand Down
12 changes: 12 additions & 0 deletions tests/test_common.js
Expand Up @@ -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 })
})
})
})

Expand Down

0 comments on commit b37c57f

Please sign in to comment.