首页 > 解决方案 > 单元测试失败,因为 - 对象作为 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} 的对象)。如果您打算渲染一组子项,请改用数组。

让我知道我在这里做错了什么以及如何纠正它。

标签: javascriptreactjsunit-testingjestjsenzyme

解决方案


您正在尝试渲染

{
    ...x, checked: (<label className="label">
    <input type="checkbox" />
    <span className="checkbox" />
  </label>)
}

应该更像

{
    x.map(y => (
        <label>
            <input type="checkbox" />
            <span className="checkbox" />
        </label>
    )
}

推荐阅读