I'm writing some test for React Components with Jest in ES6. In one test, i need clone a json imported and mutate the cloned object, but when i mutate the object cloned, the original object mutates too!
import obj from './object.json'; // obj = { name: 'someName' }
describe('Testing a component', () => {
it('Some testing', () => {
const obj2 = Object.assign({}, obj); //Clone the object
obj2.name = 'otherName'; // Muatate the object
console.log(obj); // { name: 'otherName' }
});
})
Why this happen? Why when i mutate the cloned object, the original imported object mutates too?
Object.assign
only does a shallow clone. That means the internal objects are still pointing to the original ones.
To do a deep clone you can use Lodash or immutability-helper.