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?
Access a DOM Element Using ReactDOM.findDOMNode() . findDOMNode() is used to find a specific node from the DOM tree and access its various properties, such as its inner HTML, child elements, type of element, etc. In short, it can return all the supported DOM measurements related to the kind of element.
We access a DOM element using the current property of a reference created with the React. createRef() function. React will update this property with an actual DOM element after render and before update events. That means that we can access the DOM element in componentDidMount and componentDidUpdate functions.
Unit testing is a level of software testing where individual units/components of a software are tested. In the React world this means testing an individual React Component or pure functions.
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('#');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With