Stop querying found elements when testing react
I’ve been working through Stephen Grider’s React Testing Library and Jest course and stumbled on something that will clean up my tests: the within() function. There are many times when I find myself drilling into a part of a component to test something nested inside another element. I might take two or three hops to get there: import { within, screen } from '@testing-library/react' const table = screen.getByRole("table") const rows = within(table).getAllByRole("row") This takes two lines and, more importantly: It isn’t immediately clear what I am doing I declare the table constant when it isn’t relevant to anything With within(), you can shorten this to a single readable line: ...

