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
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.
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.
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;
Check out exists()
:
expect(wrapper.find(MyComponent).exists()).toEqual(true)
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)
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