Unit Testing in React — React Technical Interview Questions & Answers

Unit Testing in React

Unit Testing in React

  • React Testing Library: render(<Comp />), screen.getByRole / getByText, userEvent.click, assert the text/role the user sees. Jest or Vitest runs it. Test behaviour, not implementation (not wrapper.state(), not CSS class internals).
  • Example: Counter — click Increment, expect ‘1’ on screen. That’s a unit-style component test. MSW mocks network. Don’t snapshot the entire HTML of a page as your only test.
  • Unit Testing in React — output: render / click / assert text. Don’t test implementation details like state keys.

Technical Interview Tip: RTL render + userEvent + assert text.

Code Examples for Unit Testing in React

Example

// RTL idea
console.log("render(<Counter />)");
console.log("click / increment");
console.log('expect(screen.getByText("1")).toBeInTheDocument()');

Unit Testing in React — output: render / click / assert text. Don’t test implementation details like state keys.

How to Explain Unit Testing in React to an Interviewer

Explain Unit Testing as if you are teaching a junior — definition, then one tiny UI.

RTL + Vitest/Jest. user behaviour, not internals.

What does the example show on screen (or print), and what does that prove?

Unit Testing in React — output: render / click / assert text

What mistake do freshers make with Unit Testing?

Ex : click → text on screen.