1

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

我正在使用 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)

实际上完美地工作

我的组件不符合规范。

4

1 回答 1

1

尝试在每个it. 然后,当您使用 Jest 时,您可以使用该.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()
  })
于 2017-02-17T17:41:01.643 回答