Basic reactivity rendering test: exists () with respect to length

In your basic React component rendering tests, which approach is more robust?

const wrapper = shallow(<MyComponent />);

expect(wrapper.exists()).to.equal(true);
expect(wrapper.find('div').length).to.equal(1);

      

Same for testing rendered child components:

const wrapper = shallow(<MyComponent />);

expect(wrapper.find(MyChildComponent).exists()).to.equal(true);
expect(wrapper.find(MyChildComponent).length).to.equal(1);

      

I find it exists()

much more idiomatic. But I see that most people use the version length

in their tests. What are the trade-offs, if any?

+3


source to share


2 answers


exists()

is just a sugar wrapper length.

 exists() {
    return this.length > 0;
 }

      



So which one suits you like you do, I think is exists()

more descriptive and prefers to use it.

+2


source


Do you even need a first check? the wrapper should exist anyway when you do small things on your component I guess.

If you need this, I like to use exists()

in the first example more than finding the div from the child. What happens if you change this div a gap later, your test case will fail unnecessarily, even if we only care about creating the wrapper.

For the second example, it makes sense to use .exists()

when MyChildComponent

may be displayed 1 or more times in the future, it depends what your use case is.



It makes sense to use .length

of 1 when you ever want to MyChildComponent

appear once, so that the test will fail if another developer shows up and displays it somewhere else in the component.

90% of the time I use .length

it because it is usually more appropriate and less errors to be accurate with the number of elements you want to render.

+1


source







All Articles