Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the simplest way of testing that a React Component contains a html node with enzyme?

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

like image 505
Vlad Nicula Avatar asked Apr 22 '16 13:04

Vlad Nicula


People also ask

How would you test the React components using Jest and enzymes?

Both Jest and Enzyme are meant to test the react applications. Jest can be used with any other Javascript framework, but Enzyme is meant to run on react only. Jest can be used without Enzyme, and snapshots can be created and tested perfectly fine. But the Enzyme adds additional functionality to it.

What is Jest and Enzyme?

Jest and Enzyme are tools which are used in tandem to test React components, and are used in the C#Bot testing framework for unit tests of client-side components. While they are used in this context to test react components, Jest is not specific to React, and can be used in other JavaScript applications.


3 Answers

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;
like image 114
JMM Avatar answered Oct 01 '22 09:10

JMM


Check out exists():

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

like image 36
Piotr Avatar answered Oct 01 '22 07:10

Piotr


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)
like image 24
Cody Avatar answered Oct 01 '22 08:10

Cody