I have a component that depending on the props passed to it, renders different child components.
I am using jestjs for testing, and I want to assert that that the "parent" component renders the appropriate children/child based on the props passed in the parent component.
a simplified snippet :
the parent component
import ComponentA from './componentA'
import ComponentB from './componentB'
function ParentComponent(props) {
const { step } = props
switch(step) {
case 'A':
return (<ComponentA />)
case 'B':
return (<ComponentB />)
}
}
the test
import ParentComponent from './ParentComponent'
import ComponentA from './ComponentA'
import ComponentB from './ComponentB'
const renderCompo = (props = {}) => mount(
<ParentComponent step={'A'} {...props} />
)
describe('ParentComponent', () => {
it('should render the <ComponentA /> as its child when passed `A` as the value of step props', () => {
const renderedComponent = renderCompo()
// I know this is not correct use of find but this serve as illustration of what I'm trying to assert
expected(renderedComponent.find(<ComponentA />).length).toEqual(1)
})
it('should NOT render the <ComponentB /> as its child when passed `A` as the value of step props', () => {
const renderedComponent = renderCompo()
// I know this is not correct use of find but this serve as illustration of what I'm trying to assert
expected(renderedComponent.find(<ComponentA />).length).toEqual(0)
})
it('should render the <ComponentB /> as its child when passed `B` as the value of step props', () => {
const renderedComponent = renderCompo({ step: 'B' })
expected(renderedComponent.find(<ComponentB />).length).toEqual(1)
})
it('should render the <ComponentA /> as its child when passed `B` as the value of step props', () => {
const renderedComponent = renderCompo({ step: 'B' })
expected(renderedComponent.find(<ComponentB />).length).toEqual(0)
})
})
I tried various way to assert this but with no luck.
I know how to use the find method to - for instance - search a div
or a h3
, but I would like to test the children against a react component and not the root DOM node the child renders as it might be the same DOM node in different components.
––––––––––––––––––– EDIT : –––––––––––––––––––
Using
expect(renderedComponent.find(ComponentA).length).toEqual(1)
actually work perfectly
My component was not up to spec.