gpt4 book ai didi

unit-testing - 如何在 React 0.14 的单元测试中检查 DOM 节点的 props?

转载 作者:行者123 更新时间:2023-12-03 13:20:07 24 4
gpt4 key购买 nike

将 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 元素?

最佳答案

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

debugger

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

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

关于unit-testing - 如何在 React 0.14 的单元测试中检查 DOM 节点的 props?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32246645/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com