within() in React Testing Library

Normally with React Testing Library, you use the functions such as screen.getByText(). But this is like a global search.

Sometimes you might already have an element (from a getByText() call for example) - and within that element you want to find something else.

import {
  render,
  screen,
  within,
} from '@testing-library/react';

function SomeComponent() {
  return (
    <div>
      <div data-testid="user1">
        <h1>Bart</h1>
      </div>
      <div data-testid="user2">
        <h1>Lisa</h1>
      </div>
    </div>
  );
}

test('user 1 has a name of Bart', () => {
  render(<SomeComponent />);
  const firstUserDiv =
    screen.getByTestId('user1');
  const firstUserDivHeading = within(
    firstUserDiv
  ).getByRole('heading');
  expect(
    firstUserDivHeading
  ).toHaveTextContent('Bart');
});

Loading full lesson content & code...

Ready to try running tests for this lesson?