Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest - How to find rendered DOM component with id?

Tags:

reactjs

jestjs

I am writing a simple Jest test that verifies that my component rendered. I see that React's TestUtils has functions for finding rendered components by class or by tag, but not by their ID attribute. There is a findAllInRenderedTree function, but the documentation does not explain what the callback should expect.

I would guess that the callback will receive some sort of element object, which is not a normal DOM element or an ordinary React component. What exactly is passed to findAllInRenderedTree's callback, and how am I supposed to get its attributes, or at least its ID?

I would just console.log the callback's arguments, but I am having a hard time getting console to work in a Jest test.

like image 722
Dan Ross Avatar asked Jun 23 '15 10:06

Dan Ross


People also ask

How do you get the DOM React component?

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 I know if a component is rendered?

Using React DevTools to highlight what components rerendered To enable it, go to "Profiler" >> click the "Cog wheel" on the right side of the top bar >> "General" tab >> Check the "Highlight updates when components render." checkbox.

How do you find the ID of a React component?

To get the id of the element on click in React: Set the onClick prop on the element to a function. Access the id of the element on the currentTarget property of the event . For example, event.currentTarget.id returns the element's id .

How do I find ID in React test library?

const input = dom. getElemenById('firstinput'); //or const input = dom. getById('firstinput'); reactjs.


1 Answers

The callback argument of findAllInRenderedTree gets passed a component instance and should return a boolean that indicates whether the component should be kept in the output array.

In your case, to find all rendered DOM components with a given id:

function scryRenderedDOMComponentsWithId(tree, id) {
  return TestUtils.findAllInRenderedTree(tree, function(inst) {
    return TestUtils.isDOMComponent(inst) && inst.getAttribute("id") === id;
  });
}

If you need to test against attributes of the actual DOM Node, you can use React.findDOMNode(inst) to retrieve the DOM Node of a given component instance.

like image 106
Alexandre Kirszenberg Avatar answered Sep 17 '22 11:09

Alexandre Kirszenberg