I have this code:
wrapper.find('.table-year-head button').at(1).simulate('click');
wrapper
.find('.table-months')
.at(1)
.find('input[type="checkbox"]')
.forEach(node => {
expect(node.props().checked).toEqual(true);
});
I know that I can use data-testid for the selectors but how can I select the nth?
You can use a getAllBy query:
const table = wrapper.getAllByRole('table')[1]
fireEvent.click(within(table).getByRole('button'));
The problem is that you wouldn't be able to use CSS selectors the way you are doing with Enzyme. React testing library is all about semantic. I would recommend you to add labels to your tables using aria-label attribute:
<table className="years" aria-label="Year table">
...
This way, you would be able to do:
const yearTable = wrapper.getByRole('table', {name: 'Year table'});
fireEvent.click(within(yearTable).getByRole('button'));
const monthTable = screen.getByRole('table', {name: 'February table'});
const checkbox = within(monthTable).getByRole('checkbox')
fireEvent.click(checkbox);
expect(checkbox).toBeChecked();