TypeError: Cannot assign to read only property 'x' of object '#<Object>' React/JEST

Pragam Shrivastava picture Pragam Shrivastava · Feb 20, 2018 · Viewed 24.4k times · Source

While I am writing test case for my react component I am getting

TypeError: Cannot assign to read only property 'x' of object '#'

wherein while the application run it does not throw similiar error

The code for it is pretty basic

this.props.defaultForm = true;

Why the behavior is different for test and actual application RUN?

What would be work around if I want to write a test case?

Answer

theVoogie picture theVoogie · Jul 17, 2018

There is a way to accomplish that, tho.
Create a "clone" of your object with Object.assign() method

let clone = Object.assign({}, this.props);

change its values and return it as a result.

clone.defaultForm = true;
return clone;  

But take into account that Object.assign() creates a shallow copy of an object. Thus, if you need to have a deep copy, I would recommend to use following approach:

let deepClone = JSON.parse(JSON.stringify(this.props));
deepClone.defaultForm = true;
return deepClone;