【问题标题】:React Enzyme find second (or nth) nodeReact Enzyme 找到第二个(或第 n 个)节点
【发布时间】:2017-02-19 08:09:38
【问题描述】:

我正在测试一个带有 Jasmine Enzyme 浅层渲染的 React 组件。

为了这个问题的目的在这里简化...

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

MyOuterComponent 有 2 个 MyInnerComponent 实例,我想测试每个实例的 props。

我知道如何测试的第一个。我使用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 时,我没有看到类似的例子。

有人吗?

【问题讨论】:

    标签: reactjs jasmine enzyme


    【解决方案1】:

    TL;DR;

    findAll.at(1)

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

    【讨论】:

      【解决方案2】:

      如果您要测试某些东西每一个还可以考虑遍历匹配集:

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

      【讨论】:

        【解决方案3】:

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

        所以,对于你的例子:

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

        【讨论】:

        • 对我来说,at()findAll() 一起使用,可能与项目的版本有关。
        【解决方案4】:
         const component = wrapper.find('MyInnerComponent').at(1); 
         //at(1) index of element 0 to ~
        
         expect(component.prop('title')).to.equal('Good-bye');
        

        【讨论】:

          猜你喜欢
          • 2012-12-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-01-21
          • 1970-01-01
          • 2013-01-22
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多