0

How to look for the second to last child node returned by the find() method of Enzyme? The last child could be found with .last(), but the one before that?

I know it doesn't return an array, but what I would expect to do is something like:

const elementsArray = wrapper.find('element');
const secondToLastElement = elementsArray.at(elementsArray.length - 1);

Thanks in advance.

skyboyer
  • 15,149
  • 4
  • 41
  • 56
ElDuderino
  • 29
  • 7

1 Answers1

0

@EIDuderino

Ideally, your solution should also work by subtracting 2 from total length, since '.find' return iterable object.

Please find below as updates:

const elementsArray = wrapper.find('element');
const secondToLastElement = elementsArray.at(elementsArray.length - 
    2);

Alternatively, I believe we can use below solution to find count and then use '.at' to find the second last element. which is not the ideal solution but can be of help.

let totalElements = 0;
component.find('MyInnerComponent').forEach( (node) => { 
    totalElements++; });

once we do have total count, we can make use of code you have suggested.

Below are links which might help add to the answer

React Enzyme find second (or nth) node.

I think alternatively you can use '.get' as well, if this helps the scenario. However, I am sure you already been through the enzyme documentation, but putting the link for reference on '.get' and '.at' respectively.

I hope, this helps.

Hemant Kumar
  • 121
  • 5
  • Thanks @Hemant Kumar. The problem is not so much as how to find an element when I know the position, but how to find it starting from the end. Something like: 'No matter how many there are, give me the one before the last one.' – ElDuderino Mar 25 '20 at 09:45
  • Hi, I think we can find count by using '.forEach' on find(), as: component.find('MyInnerComponent').forEach( (node) => { count++; }); and then find second last item. If this helps – Hemant Kumar Mar 25 '20 at 10:50
  • Perfect. The idea worked! so Basically: for each element, add 1 to the count and use the count to count from the last element afterwards. Could you add your comment as answer so I can mark it as solving the problem? Thank you. – ElDuderino Mar 26 '20 at 07:36