React Enzyme 找到第二个(或第 n 个)节点

React Enzyme find second (or nth) node

我正在使用 Jasmine Enzyme 浅层渲染测试 React 组件。

为了这个问题,这里进行了简化...

function MyOuterComponent() {
  return (
    <div>
      ...
      <MyInnerComponent title="Hello" />
      ...
      <MyInnerComponent title="Good-bye" />
      ...
    </div>
  )
}

MyOuterComponent 有 2 个 MyInnerComponent 实例,我想在每个实例上测试道具。

第一个我知道怎么测试。我使用 findfirst...

expect(component.find('MyInnerComponent').first()).toHaveProp('title', 'Hello');

但是,我正在努力测试 MyInnerComponent 的第二个实例。

我希望这样的东西能奏效...

expect(component.find('MyInnerComponent').second()).toHaveProp('title', 'Good-bye');

甚至这个...

expect(component.find('MyInnerComponent')[1]).toHaveProp('title', 'Good-bye');

当然,以上两种方法都行不通。

我觉得我错过了显而易见的事情。

但是当我查看 docs 时,我没有看到类似的例子。

有人吗?

你想要的是.at(index)方法:.at(index) .

因此,对于您的示例:

expect(component.find('MyInnerComponent').at(1)).toHaveProp('title', 'Good-bye');

 const component = wrapper.find('MyInnerComponent').at(1); 
 //at(1) index of element 0 to ~

 expect(component.prop('title')).to.equal('Good-bye');

如果你要测试某些东西每个也考虑遍历匹配的集合:

component.find('MyInnerComponent').forEach( (node) => {
    expect(node.prop('title')).toEqual('Good-bye')
})

TL;DR;

使用 findAll.at(1)

const innerComponent = component.findAll('MyInnerComponent').at(1);
expect(innerComponent).toHaveProp('title', 'Good-bye');