0

Imagine you have the following two components

class Parent ... {    
    
    render() {
        let child;
        if(this.props.children[0].type.IS_CHILD){ 
            this.props.children[0].isInsideParent = true;
            child = this.props.children[0];
            return <div>{child}</div>
        }
        return <div>ERROR</div>
    }
}

class Child ... {
    
    public static IS_CHILD = true;
   
    render() {
        let parent;
        if(this.props.isInsideParent) 
            return <div>OK</div>;
        return <div>ERROR</div>
    }
}

If you try to test using enzyme as follow:

const wrapper1 = shallow(<Parent><Child></Child></Parent>)
const wrapper2 = shallow(<Parent><Child></Child></Parent>).dive();
const wrapper3 = mount(<Parent><Child></Child></Parent>)

It will work only with mount because it's the only one rendering the inner component as well (therefore children[0].type is defined as class Child, so it has an IS_CHILD property).

Instead, with shallow, it tries to render the Parent component, but when it tries to see if it internally has a Child element, it won't see it (children[0].type would be equal to function ShallowRenderStub(_a))

Is there a way to just test this very specific case with enzyme?

igol
  • 127
  • 1
  • 8

1 Answers1

1

Your parent logic relies on rendering a specific child component. And you got your answer yourself - you should use mount since it renders the children components.

The difference between shallow() and mount() is that shallow() tests components in isolation from the child components they render, while mount()goes deeper and tests a component's children.

Source: When should you use render and shallow in Enzyme / React tests?

Svetoslav Petkov
  • 1,117
  • 5
  • 13