如何在React 0.14的单元测试中检查DOM节点的道具?

mik*_*1aj 10 unit-testing reactjs

在将React升级0.13到之后v0.14.0-beta3,我在单元测试中收到了很多这样的警告:

Warning: ReactDOMComponent: Do not access .props of a DOM node; instead, recreate the props as `render` did originally or read the DOM properties/attributes directly from this node (e.g., this.refs.box.className). This DOM node was rendered by `Button`.
Run Code Online (Sandbox Code Playgroud)

它们是由我的单元测试引起的,例如:

it('should render to a <a> when href is given', function () {
    var button = TestUtils.renderIntoDocument(<Button className="amazon" href="#">Hello</Button>);
    expect(TestUtils.scryRenderedDOMComponentsWithTag(button, 'button').length).toBe(0);
    expect(TestUtils.scryRenderedDOMComponentsWithTag(button, 'a').length).toBe(1);
    expect(TestUtils.scryRenderedDOMComponentsWithTag(button, 'a')[0].props.href).toBe('#');
    expect(TestUtils.scryRenderedDOMComponentsWithTag(button, 'a')[0].props.className).toBe('amazon Button');
});
Run Code Online (Sandbox Code Playgroud)

我该如何解决?是否有任何推荐的测试方法来测试这样的DOM元素?

mik*_*1aj 16

在调试器中,我发现这些元素(例如,在我的情况下TestUtils.scryRenderedDOMComponentsWithTag(button, 'a')[0])实际上是DOM元素,只添加了一些React属性(比如propsstate).

调试器

所以现在,有了这些知识,我可以根据DOM属性和属性编写我的断言,例如:

expect(b.getAttribute('href')).toEqual('#');
Run Code Online (Sandbox Code Playgroud)

  • DOM节点上的.props等仅作为迁移​​辅助存在,并将在0.15中删除. (4认同)