React / Next.js

React Testing

React Testing Library, Jest, Vitest, component testing, mocking, user interactions, coverage

20 interview questionsยท
Mid-Level
1

What is the main difference between getBy, queryBy and findBy in React Testing Library?

Answer

getBy throws an error if the element doesn't exist (synchronous assertions), queryBy returns null if the element doesn't exist (checking absence), and findBy returns a Promise for async elements. Use getBy by default for elements that must exist, queryBy to verify an element is not present, and findBy to wait for an element to appear after a delay.

2

What is the main advantage of getByRole over getByTestId?

Answer

getByRole encourages accessibility best practices by targeting elements by their semantic ARIA role (button, textbox, heading), which improves component accessibility for screen readers. getByTestId requires adding artificial data-testid attributes that provide no value to end users. React Testing Library recommends prioritizing getByRole, getByLabelText and getByText before getByTestId.

3

How to test the conditional rendering of an element that is NOT present in the DOM?

Answer

Use queryBy to verify an element's absence, as it returns null instead of throwing an error. Example: expect(screen.queryByText('Error')).toBeNull() or expect(screen.queryByText('Error')).not.toBeInTheDocument(). getBy would throw an error and fail the test, while findBy waits for the element to appear (timeout if absent).

4

Why does React Testing Library recommend NOT testing implementation details?

5

What is the difference between render and screen in React Testing Library?

+17 interview questions

Master React / Next.js for your next interview

Access all questions, flashcards, technical tests, code review exercises and interview simulators.

Start for free