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

ev7lccsx  于 2023-06-04  发布在  Jest
关注(0)|答案(3)|浏览(710)

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

类型错误:无法分配给对象“#”的只读属性“x”

其中,当应用程序运行时,它不会抛出类似的错误

  • 代码很简单 *

this.props. default = true;

为什么测试和实际应用程序运行的行为不同?
如果我想写一个测试用例,应该怎么做?

z18hc3ub

z18hc3ub1#

有一种方法可以做到这一点;
使用Object.assign()方法或JavaScript spread操作符创建对象的“clone
let clone = Object.assign({}, this.props);

let clone = { ...this.props };
然后,更改所需的值并返回克隆结果。

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;

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

raogr8fs

raogr8fs2#

syntax-punk答案
JavaScript有一个内置的函数来创建任何对象的深层副本。

const copiedObject = structuredClone(existingObject);

还有

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

JavaScript中的Spread运算符不会创建对象的深层副本

muk1a3rh

muk1a3rh3#

不能更改零部件的特性。它是只读。
如果你想的话,可以改变它。必须使用connect from redux和函数mapStateToProps
您可以在这里找到更多信息:https://redux.js.org/basics/usage-with-react#implementing-container-components

相关问题