5
votes

When unit testing react components I often check for the existence of a child node based on the presence or content of a prop.

With enzyme, I find the element using .find on either the shallow or mount wrapper and then check if the length of that is 1. With chai, this would look like this:

const wrapper = shallow(<MYReactComponent/>);
const innerNode = wrapper.find('some-css-selector');
expect(innerNode.length).to.equal(1);

Is there a better way of checking

3

3 Answers

6
votes

Say you're testing for existence via selector as in your example and need to use a method that returns ShallowWrapper, then yes you need to use .length. But you don't necessarily need separate statements for it:

const wrapper = shallow(<MYReactComponent />);
expect(wrapper.find('some-css-selector').length).to.equal(1);

For that matter you could consolidate the whole thing in a case like this if you want:

expect(
  shallow(<MYReactComponent />)
  .find('some-css-selector').length
).to.equal(1);

If you're testing based on component type / props then you may be able to use contains(), which returns boolean:

const wrapper = shallow(<MYReactComponent />);
expect(wrapper.contains(
  <div class="something">
    <span>content</span>
  </div>
)).to.be.true;
3
votes

Check out exists():

expect(wrapper.find(MyComponent).exists()).toEqual(true)

1
votes

Can skip find by directly using exists

expect(wrapper.exists('some-css-selector')).to.equal(true)

Also works with other React Components nicely

import SomeOtherReactElement from 'path/to/SomeOtherReactElement';

...
...

expect(wrapper.exists(SomeOtherReactElement)).to.equal(true)