Jest - How to find rendered DOM component with id?

9.6k views Asked by At

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.

1

There are 1 answers

1
Alexandre Kirszenberg On BEST ANSWER

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.