-->

断言反应组分子女存在/使用jestjs缺席(assert react component child

2019-09-27 03:55发布

我有一个组件,它根据传递给它的道具,呈现不同的子组件。

我使用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方法-例如-搜索divh3 ,但我想,以测试对一个反应成分的儿童和没有孩子渲染,因为它可能是在同一个DOM节点根DOM节点不同的组件。

-------------------编辑:-------------------

运用

expect(renderedComponent.find(ComponentA).length).toEqual(1)

实际工作完美

我的部件没有达到规范。

Answer 1:

尽量明确你在每个想要的道具元件安装it 。 然后,当你使用玩笑,你可以使用.toMatchSnapshot()方法。 然后,您可以打开生成,以确保一切都呈现你所期望的快照文件。

注意:您将需要酶到JSON用于下面的例子上班

it('should render the <ComponentA /> as its child when passed `A` as the value of step props', () => {
    const wrapper = mount(<ParentComponent step={'A'} />)
    expected(toJson(wrapper)).toMatchSnapshot()
  });
it('should render the <ComponentB /> as its child when passed `B` as the value of step props', () => {
    const wrapper = mount(<ParentComponent step={'B'} />)
    expected(toJson(wrapper)).toMatchSnapshot()
  })


文章来源: assert react component child(ren) existence/absence using jestjs