我有一个组件,根据传递给它的道具,呈现不同的子组件。
我正在使用 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 方法 - 例如 - 搜索 adiv
或 a h3
,但我想针对反应组件而不是子节点呈现的根 DOM 节点测试子节点,因为它可能是不同组件中的相同 DOM 节点.
––––––––––––––––––– 编辑:–––––––––––––––––––––––––––––</p>
使用
expect(renderedComponent.find(ComponentA).length).toEqual(1)
实际上完美地工作
我的组件不符合规范。