【发布时间】:2018-07-30 19:28:17
【问题描述】:
当我为我的反应组件编写测试用例时,我得到了
TypeError:无法分配给对象“#”的只读属性“x”
当应用程序运行时它不会抛出类似的错误
它的代码非常基本
this.props.defaultForm = true;
为什么测试和实际应用程序 RUN 的行为不同?
如果我想写一个测试用例有什么办法?
【问题讨论】:
标签: reactjs jestjs enzyme babel-jest
当我为我的反应组件编写测试用例时,我得到了
TypeError:无法分配给对象“#”的只读属性“x”
当应用程序运行时它不会抛出类似的错误
它的代码非常基本
this.props.defaultForm = true;
为什么测试和实际应用程序 RUN 的行为不同?
如果我想写一个测试用例有什么办法?
【问题讨论】:
标签: reactjs jestjs enzyme babel-jest
有办法做到这一点;
使用 Object.assign() 方法或 JavaScript spread operator 为您的对象创建一个“克隆”
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;
在这里,“字符串化”对象然后将其解析回来将创建对象的全新深度克隆副本。
【讨论】:
您不能更改组件的属性。它是只读的。
如果你想改变它。您必须使用来自redux 的connect 和函数mapStateToProps。
您可以在这里找到更多信息:https://redux.js.org/basics/usage-with-react#implementing-container-components
【讨论】:
this.prop还是this.props?
this.props(只读)。