I am testing a component that conditionally renders a wrapped component. I am using enzyme and jest and the root component is rendered through the shallow() method. The issue is testing if the Root component contains the wrapped component.
How would I test if the wrapped component exists without using the mount() render method?
hoc.component.jsx
export function HOC(Component) {
render() {
return <Component />
}
}
wrapped.component.jsx
class WrappedComponent extends React.Component {
...
}
export default HOC(WrappedComponent)
root.component.jsx
class RootComponent extends React.Component {
render() {
return (
condition ? ... :
<WrappedComponent/>
)
}
}
When testing the root.component.jsx I would like to check if the WrappedComponent exists.
root.component.spec.js import { WrappedComponent } from 'WrappedComponent'
const wrapper = shallow(<RootComponent {...props}/>);
wrapper.find(WrappedComponent).length => returns 0
If I log wrapper.debug() I see the following:
...<HOC(WrappedComponent) />
How would I test the existence of the WrappedComponent while testing the RootComponent?
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.
shallow method is used to render the single component that we are testing. It does not render child components. In Enzyme version less than 3, the shallow method does not have the ability to access lifecycle methods. But in Enzyme version 3, we have this ability.
As of Enzyme v3, the shallow API does call React lifecycle methods such as componentDidMount and componentDidUpdate .
Shallow renders the root node and returns a shallow wrapper around it. It must be a single-node wrapper.
It should be possible to assert the existence of a component, as long as WrappedComponent
in tests is not original component class but a component wrapped in HOC, i.e. HOC(WrappedComponent)
.
If HOC(WrappedComponent)
is default export, it should be:
import WrappedComponent from 'WrappedComponent'
...
const wrapper = shallow(<RootComponent {...props}/>);
expect(wrapper.find(WrappedComponent).length).toBe(1);
You can use the selector 'HOC(WrappedComponent)'
:
test('WrappedComponent is rendered', () => {
const wrapper = shallow(<RootComponent {...props}/>);
expect(wrapper.find('HOC(WrappedComponent)').length).toEqual(1);
}
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