如何在 React 0.14 的单元测试中检查 DOM 节点的道具? [英] How to check props of a DOM node in an unit test in React 0.14?

查看:26
本文介绍了如何在 React 0.14 的单元测试中检查 DOM 节点的道具?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

警告:ReactDOMComponent:不要访问 DOM 节点的 .props;相反,像 `render` 最初所做的那样重新创建 props 或直接从该节点读取 DOM 属性/属性(例如,this.refs.box.className).这个 DOM 节点是由 `Button` 渲染的.

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

it('should render to a 

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

expect(b.getAttribute('href')).toEqual('#');

After upgrading React from 0.13 to v0.14.0-beta3, I got a lot of warnings like this in my unit tests:

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`.

They are caused by my unit tests, for example:

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');
});

How do I fix this? Is there any recommended practice for testing DOM elements like this?

解决方案

In the debugger I discovered that these elements (like, in my case, TestUtils.scryRenderedDOMComponentsWithTag(button, 'a')[0]) are in fact DOM elements with just some React properties added (like props and state).

So now, with this knowledge, I can write my assertions based on DOM attributes and properties, like:

expect(b.getAttribute('href')).toEqual('#');

这篇关于如何在 React 0.14 的单元测试中检查 DOM 节点的道具?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆