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

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

当我为我的 React 组件编写测试用例时,我得到

TypeError: 无法分配给对象“#”的只读 属性 'x'

其中应用程序 运行 不会抛出类似错误

它的代码非常基础

this.props.defaultForm = true;

为什么测试和实际应用的行为不同运行?

如果我想编写一个测试用例,有什么解决方法?

您不能更改组件的属性。它是只读的。

如果你想改变它。您必须使用 redux 中的 connect 和函数 mapStateToProps.

您可以在此处找到更多信息:https://redux.js.org/basics/usage-with-react#implementing-container-components

有一种方法可以做到这一点;

使用 Object.assign() method, or JavaScript spread operator

创建对象的“克隆

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

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

然后,更改您需要的值,return 克隆结果。

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

但请注意 Object.assign() 创建对象的浅表副本。因此,如果您需要深拷贝,我建议使用以下方法:

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

在这里,“字符串化”对象然后再解析它会创建对象的全新深度克隆副本。