【问题标题】:Unit testing failing because of - Objects are not valid as a React child单元测试失败,因为 - 对象作为 React 子对象无效
【发布时间】:2019-09-30 06:51:05
【问题描述】:

以下是我在其中测试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} 的对象。 如果您打算渲染一组子项,请改用数组。

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

【问题讨论】:

  • 你能展示一下在渲染时如何使用组件状态中的myList吗?

标签: javascript reactjs unit-testing jestjs enzyme


【解决方案1】:

你正在尝试渲染

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

应该更像

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-27
    • 2018-05-27
    • 2021-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多