【问题标题】:How to check props of a DOM node in an unit test in React 0.14?如何在 React 0.14 的单元测试中检查 DOM 节点的道具?
【发布时间】:2015-11-21 16:11:37
【问题描述】:

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

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

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

我该如何解决这个问题?有没有推荐的做法来测试这样的 DOM 元素?

【问题讨论】:

  • 您不需要像这样测试道具的值,因为您确切知道自己传递的是什么。组件本身不能改变 props 的值,所以 props 永远是你给它的。
  • 我正在检查一个子节点的道具(所以不是我刚刚通过的那些),所以这确实有意义。

标签: unit-testing reactjs


【解决方案1】:

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

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

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

【讨论】:

  • DOM 节点上的 .props 等仅作为迁移​​辅助存在,将在 0.15 中删除。
  • 感谢您提供的信息。那你有替代解决方案吗?
  • 不,您的解决方案是正确的!我只是说他们不会在未来的版本中添加 React 属性——这就是你现在使用这些属性时会收到警告的原因。
【解决方案2】:

要修复警告,只需直接调用一个道具。 例如:

警告代码:

this.refs.input.props.name

固定代码:

this.refs.input.name

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-21
    • 1970-01-01
    • 1970-01-01
    • 2016-10-12
    • 1970-01-01
    • 2020-11-09
    相关资源
    最近更新 更多