javascript - 单元测试失败,因为 - 对象作为 React 子对象无效
问题描述
以下是我mytestFunc
在复选框选中条件下测试调用的代码。
复选框 -
<input id="mycheck" type="checkbox" onClick={this.mytestFunc} />
mytestFunc函数 -
mytestFunc = e => {
const mockdata = this.state.myList
const newArr = mockdata.map(x => e.target.checked ? {
...x, checked: (<label className="label">
<input type="checkbox" />
<span className="checkbox" />
</label>)
} : {
...x, checked: (<label className="label">
<input type="checkbox" />
<span className="checkbox" />
</label>) })
this.setState({ myList: newArr })
}
我正在使用 jest/enzyme 对其进行测试-
it('test mytestFunc function', () => {
const component = mount(<MyComponent {...props} />);
const customEvent = {
"target": {
"checked": true
}
}
const dataList = [
{
"id": "DS64XX123",
"name": "test",
"gender": "male"
]
component.setState({ myList: dataList });
component.instance().mytestFunc(customEvent);
expect(component.state().myList).toBe(true);
})
错误 -
Invariant Violation:对象作为 React 子对象无效(发现:具有键 {$$typeof, type, key, ref, props, _owner, _store} 的对象)。如果您打算渲染一组子项,请改用数组。
让我知道我在这里做错了什么以及如何纠正它。
解决方案
您正在尝试渲染
{
...x, checked: (<label className="label">
<input type="checkbox" />
<span className="checkbox" />
</label>)
}
应该更像
{
x.map(y => (
<label>
<input type="checkbox" />
<span className="checkbox" />
</label>
)
}
推荐阅读
- amazon-web-services - 如何使用 Cloudfront 或 Route 53 将域重定向到域路径?
- kubernetes - 在 minikube 中运行 ReportPortal
- java - 我错了还是结果错了?
- c++ - 如何用 g++ 编译 opus-codel
- swift - SwiftUI:可选类型“绑定”的值
?必须解包为 'Binding 类型的值 ' - ansible - 在 Ansible 中访问 JSON 格式列表的每个键的值
- list - 反向方案
- python - 为帐户抓取 Instagram 关注者
- mqtt - ESP32 DevKit C v4 - 在命令 AT+MQTTSUB 到 Thingsboard 时断开/错误
- json - 如何将 json 数据添加到我的 xcode 项目中?