
React Testing
React Testing Library, Jest, Vitest, component testing, mocking, user interactions, coverage
1What is the main difference between getBy, queryBy and findBy in React Testing Library?
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.
2What is the main advantage of getByRole over getByTestId?
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.
3How to test the conditional rendering of an element that is NOT present in the DOM?
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).
Why does React Testing Library recommend NOT testing implementation details?
What is the difference between render and screen in React Testing Library?
+17 interview questions
Other React / Next.js interview topics
JavaScript Essentials
React Fundamentals
React Hooks
Component Lifecycle
React Router
State Management with Context
Forms & Controlled Components
Data Fetching & API
React Query (TanStack Query)
Styling & CSS-in-JS
Next.js Fundamentals
TypeScript with React
Next.js Data Fetching
Next.js Server Actions
Next.js Routing & Navigation
Next.js API Routes
Next.js Metadata & SEO
Next.js Middleware & Auth
Zustand State Management
React Performance Optimization
Error Boundaries & Error Handling
Advanced React Patterns
Next.js Advanced Features
Next.js Deployment & Production
Architecture & Design Patterns
React Server Components
Next.js Internationalization
React Security & Best Practices
Master React / Next.js for your next interview
Access all questions, flashcards, technical tests, code review exercises and interview simulators.
Start for free