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.
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.
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.
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 .
const input = dom. getElemenById('firstinput'); //or const input = dom. getById('firstinput'); reactjs.
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.
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