6

I'm trying to write tests for some d3 elements that are rendered via react component, and I was hoping to be able to pick out some of the svg elements on the page and check their width to see if they're behaving as expected.

I'm not entirely sure what the react test-utils docs are expecting when they say ReactComponent tree.

array scryRenderedDOMComponentsWithClass(ReactComponent tree, string className)

I'm rendering my component into the document via:

  var component = TestUtils.renderIntoDocument(
    <ProgressCircle percentage={75} />
  );

And I'm able to successfully check for a css className by doing:

  it('should render an element with the class "progress-circle"', function() {
    var circleContainer = TestUtils.findRenderedDOMComponentWithClass(component, 'progress-circle');
    expect(circleContainer).toBeDefined();
  });

But I don't understand what I need to provide to some of these find / scry methods that expect a ReactComponent tree.

http://facebook.github.io/react/docs/test-utils.html

Edit:

For more clarification, the rendered DOM for this component looks like this:

<div class="progress-circle">
  <svg>
    <g>
    </g>
  </svg>
</div>

... and I'm trying to find the element.

1 Answer 1

7

From what I understand, TestUtils.renderIntoDocument() returns a ReactComponent tree. Then you can pull individual components out of that tree to test them.

For example, this test passes for me.

it('demonstrates the ReactComponent tree', function() {
  var React = require('react/addons');
  var TestUtils = React.addons.TestUtils;
  var MyComponent = require('../MyComponent.jsx');

  var renderedTree = TestUtils.renderIntoDocument(<MyComponent />);
  var renderedMyComponent = TestUtils.findRenderedDOMComponentWithClass(renderedTree, 'my-component')

  expect(TestUtils.isDOMComponent(renderedMyComponent)).toBe(true);
});

So if you're just rendering a single component, it will be the root of the renderedTree. But you still have to find the rendered MyComponent inside the renderedTree before you can check assertions against it.

1
  • Just to add to this, renderIntoDocument is a very basic wrapper around ReactDOM.render. According to the docs it returns a ref to the root component/element being rendered. So I assume a "tree" simply refers to a component instance or DOM element which acts as the root. It also says that functional components will return null, so beware. At this time, using this returned ref is discouraged because of upcoming changes, and it is recommended you create a ref the normal way instead.
    – Inkling
    Jul 18, 2018 at 9:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.