我有一个组件,它根据传递给它的道具,呈现不同的子组件。
我使用jestjs进行测试,我想断言,即“父”组件呈现基于父组件通过道具适当的孩子/儿童。
简化的片段:
父组件
import ComponentA from './componentA'
import ComponentB from './componentB'
function ParentComponent(props) {
const { step } = props
switch(step) {
case 'A':
return (<ComponentA />)
case 'B':
return (<ComponentB />)
}
}
考试
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)
})
})
我尝试了各种方法来断言这个,但没有运气。
我知道如何使用find方法-例如-搜索div
或h3
,但我想,以测试对一个反应成分的儿童和没有孩子渲染,因为它可能是在同一个DOM节点根DOM节点不同的组件。
-------------------编辑:-------------------
运用
expect(renderedComponent.find(ComponentA).length).toEqual(1)
实际工作完美
我的部件没有达到规范。