Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
145
rated 0 times [  148] [ 3]  / answers: 1 / hits: 5150  / 2 Years ago, tue, february 8, 2022, 12:00:00

I have added the below jest unit test to render a component and I am expecting some of its elements using "getAllByText" as there are multiple similar elements. I got a review comment to loop over the list of element if there are more than 1 and expect each of them to be visible. Can someone please help me in modifying the test to loop over all the elements.


it('should render seat total wrapper on small breakpoint', () => {
render(
<MockViewportProvider viewSize={ViewSizes.SMALL}>
<SeatMapContext.Provider value={{ state: contextObj, dispatch: noop }}>
<SeatMapCabinAndSeatWrapper
flightSeatMapPlaneData={seatMapPlanesData}
flightLegsDetails={FlightLegsDetails}
onChangeLegIndex={jest.fn}
selectedLegIndex={0}
handleLegendButtonClick={jest.fn()}
handleApplySeatSelection={handleApplySeatSelection}
/>
</SeatMapContext.Provider>
</MockViewportProvider>
);
expect(screen.getByRole('button', { name: 'Next Flight' })).toBeVisible();
expect(screen.getAllByText('$276.24')[0]).toBeVisible();
});

Review comments -> "if there are expected to be more than 1 item then please loop over the list and expect each element to be visible
if there should only be 1 item then please determine how to use getByText".


More From » reactjs

 Answers
0

Just use a for loop.


for (const element of screen.getAllByText('$276.24')) {
expect(element).toBeVisible();
}

For an implementation with no for..of loop:


const list = screen.getAllByText('$276.24');
for (let i = 0; i < list.length; i++) {
expect(list[i]).toBeVisible();
}

Or:


screen.getAllByText('$276.24').forEach((element) => {
expect(element).toBeVisible();
});

[#383] Thursday, February 3, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jennie

Total Points: 593
Total Questions: 102
Total Answers: 106

Location: Federated States of Micronesia
Member since Fri, Sep 16, 2022
2 Years ago
jennie questions
;