javascript - 单元测试 ReactJS 组件产生不变违规 : findComponentRoot

标签 javascript unit-testing reactjs jestjs

我开始使用 ReactJS,我想对其进行单元测试。我制作了一个简单的组件来呈现 HTML td 元素:

...
render() {
    return (
        <td>{this.props.type == 'currency' ? '$' : ''}{this.props.content}</td>
    );
}
...

我编写了一个 Jest 单元测试:

...
it('currency should prepend dollar sign', () => {
    const datapointsTd = TestUtils.renderIntoDocument(
        <DatapointsTd type="currency" content="123" />
    );

    const datapointsTdNode = ReactDOM.findDOMNode(datapointsTd);

    expect(datapointsTdNode.textContent).toEqual('$123');
});
...

但是失败并显示以下消息:

...
Warning: validateDOMNesting(...): <td> cannot appear as a child of <div>. See di
v > DatapointsTd > td.
 FAIL  __tests__\DatapointsTd-test.js (49.753s)
- DatapointsTd › it should display content in a td
  - Invariant Violation: findComponentRoot(..., .0): Unable to find element. Thi
s probably means the DOM was unexpectedly mutated (e.g., by the browser), usuall
y due to forgetting a <tbody> when using tables, nesting tags like <form>, <p>,
or <a>, or using non-SVG elements in an <svg> parent. Try inspecting the child n
odes of the element with React ID ``.
        at invariant (node_modules\react\node_modules\fbjs\lib\invariant.js:39:1
5)
...

我不确定这意味着什么,我猜测它试图将 td 元素放入 div 元素中,但是人们如何像我一样对组件进行单元测试?

最佳答案

你的猜测是对的。 td 必须是 tr 的子级,而 tr 又必须是 tbody 或 thead 的子级。我想最简单的方法就是做这样的事情

const datapointsTd = TestUtils.renderIntoDocument(
  <table>
    <tbody>
      <tr>
        <DatapointsTd type="currency" content="123" />
      </tr>
    </tbody>
  </table>
);

关于javascript - 单元测试 ReactJS 组件产生不变违规 : findComponentRoot,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36101890/

相关文章:

java - JUnit 测试自定义对象类型的 getter 方法

java - 模拟调用同一类的另一个静态方法的静态方法

php - Codeception 单元测试 php.检查是否已使用特定参数调用函数

javascript - 如何将状态属性设置为 false

reactjs - React Typescript 没有给出类型检查错误

javascript - riffwave.js 公式中的 (128 + 127 *) 部分是什么?

javascript - 将整个世界的正则表达式与多个字符串进行匹配

javascript - 谷歌浏览器中未出现视差图像

javascript - ID 中的空格并将变量放入 ID jquery

javascript - 提高 React 用户界面性能的良好实践?