9

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?

skyboyer
  • 22,209
  • 7
  • 57
  • 64
Pragam Shrivastava
  • 1,428
  • 3
  • 13
  • 20

3 Answers3

25

There is a way to accomplish that;

Create a "clone" of your object with Object.assign() method, or JavaScript spread operator

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

or

let clone = { ...this.props };

Then, change the values you need and return the clone as a result.

let clone = Object.assign({}, this.props);
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;

Here, "stringifying" the object and then parsing it back will create completely new deeply cloned copy of the object.

syntax-punk
  • 3,736
  • 3
  • 25
  • 33
0

Following up to syntax-punk answer.

JavaScript has inbuilt function to create an deep copy of any object.

const copiedObject = structuredClone(existingObject);

Also,

let clone = { ...this.props }; //This doesn't create deep copy❌

Spread operator in JavaScript doesn't create deep copy of an object

-2

You cannot change the properties of a component. it is in read only.

If you want to can change it. You must use connect from redux and the function mapStateToProps.

You can find more information here: https://redux.js.org/basics/usage-with-react#implementing-container-components

Damien
  • 287
  • 1
  • 9