[Unit testing - React] Constrain a Query to a Specific Element Using Within

Given how web pages are built nowadays, you might find yourself with multiple instances of the same element.

To avoid querying for a list of elements and then filtering them down, you can constrain your query to a specific area.

In this lesson, we are going to learn how to leverage the within helper to constrain our query to a specific element.

 

import { render, within, screen } from "@testing-library/react"
import App from "./App"

describe("App test", () => {
  it("finds a button inside a div", () => {
     render(<App />)
     const div = screen.getByTestId(/childContainer/i)
     const buttonInsideDiv = within(div).getByRole("button", {
        name: /show hidden text/i
     })
     expect(buttonInsideDiv).toBeInTheDocument()
  })
})

 

posted @ 2024-05-07 14:48  Zhentiw  阅读(1)  评论(0编辑  收藏  举报