我开始使用 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/