How to check elements are rendered with a specific sorting with react-testing-library?

Viewed 2752

With its user-centric approach, my understanding of RTL is that testing sorting of elements should look something like.

const foo = queryByText('foo');
const bar = queryByText('bar');
expect(foo).toBeInTheDocument();
expect(bar).toBeInTheDocument();
expect(foo).toShowBefore(bar); // THIS IS MY PSEUDOCODE

However, I couldn't find a .toShowBefore() or equivalent function in RTL. What's the correct way to test that content is displayed in a certain order?

2 Answers

I don't believe React Testing Library has an idiomatic way to do this. But if you can parse your DOM, then you should be able to get the textContent of various Elements and assert on that.

const select = screen.getByTestId('select');
const children = select.children;

expect(children.item(0)?.textContent).toEqual('Interface A');
expect(children.item(1)?.textContent).toEqual('Interface B');
expect(children.item(2)?.textContent).toEqual('Interface C');

You could give each row a test id:

<tr data-testid='row'>...</tr> 

and then expect the rows to be in order:

const rows = screen.getAllByTestId('row')

expect(within(rows[0]).queryByText('A')).toBeInTheDocument()
expect(within(rows[1]).queryByText('B')).toBeInTheDocument()
expect(within(rows[2]).queryByText('C')).toBeInTheDocument()
Related