React Enzyme find second (or nth) node

ReactjsJasmineEnzyme

Reactjs Problem Overview


I'm testing a React component with Jasmine Enzyme shallow rendering.

Simplified here for the purposes of this question...

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

MyOuterComponent has 2 instances of MyInnerComponent and I'd like to test the props on each one.

The first one I know how to test. I use find with first...

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

However, I'm struggling to test the second instance of MyInnerComponent.

I was hoping something like this would work...

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

or even this...

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

But of course neither of the above work.

I feel like I'm missing the obvious.

But when I look through the docs I don't see an analogous example.

Anyone?

Reactjs Solutions


Solution 1 - Reactjs

What you want is the .at(index) method: .at(index) .

So, for your example:

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

Solution 2 - Reactjs

If you are to test certain things on each one also consider iterating through the matched set:

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

Solution 3 - Reactjs

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

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

Solution 4 - Reactjs

TL;DR;

use findAll along with .at(1)

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsfletcheView Question on Stackoverflow
Solution 1 - ReactjstomView Answer on Stackoverflow
Solution 2 - ReactjsFrank NockeView Answer on Stackoverflow
Solution 3 - ReactjsD V YogeshView Answer on Stackoverflow
Solution 4 - ReactjsTaimoor ChangaizView Answer on Stackoverflow