Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check props of a DOM node in an unit test in React 0.14?

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?

like image 902
mik01aj Avatar asked Aug 27 '15 10:08

mik01aj


People also ask

How do you find the element in the DOM react?

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.

How do you read Dom in react?

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.

What is unit test cases in react JS?

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.


1 Answers

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

debugger

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

expect(b.getAttribute('href')).toEqual('#');
like image 193
mik01aj Avatar answered Nov 05 '22 20:11

mik01aj