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: ...

February 15, 2025 · 1 min · Jamal Hansen

Group JUnit Tests with @Nested

I really like the way that I can nest my JavaScript tests using describe blocks. This keeps my tests nicely organized and grouped together in functional blocks which can be super useful when you get a whole lot of tests created. describe("my component", () => { describe("validation", () => { it("ensures that user name is provided", () => { // test here }) it("ensures that password is valid", () => { // test here }) }) describe("when saved", () => { it("displays an indication that mutation is in progress", () => { // test here }) it("provides feedback of success", () => { // test here }) it("provides an error message on failure", () => { // test here }) }) }) I was not aware that you can do something like this in Java with JUnit. Reading through Pragmatic Unit Testing in Java with JUnit I found that this functionality is available by making an inner class and using the @Nested annotation. ...

February 14, 2025 · 2 min · Jamal Hansen