R

React Handbook

Clean • Professional

React Testing — Top Interview Questions & Answers

5 minute

Testing in React — Interview Questions & Answers

Ques 1: What is testing in React?

Ans: Testing in React ensures that components work as expected — rendering correctly, handling user interactions properly, and producing consistent output after changes.

Ques 2: Why is testing important in React applications?

  • Prevents regressions when making changes
  • Increases confidence during refactoring
  • Ensures reliability and consistency
  • Helps maintain code quality in large projects

Ques 3: What are the main types of tests in React?

  1. Unit Testing – Tests small, isolated pieces of code (like functions or components).
  2. Integration Testing – Tests how multiple components work together.
  3. End-to-End (E2E) Testing – Simulates real user interactions across the entire app.

Ques 4: Which tools are commonly used for testing React applications?

  • Jest – Unit testing framework
  • React Testing Library (RTL) – Tests React components behavior
  • Cypress / Playwright – End-to-End testing
  • Enzyme (older) – Component testing utility

Ques 5: What is Jest?

Ans: Jest is a JavaScript testing framework created by Facebook. It’s used for unit and integration tests, offering features like mocking, snapshots, and built-in assertions.

Ques 6: What are the benefits of using Jest?

  • Zero configuration setup
  • Snapshot testing
  • Mocking support
  • Fast parallel test execution
  • Built-in coverage reports

Ques 7: What is a test file naming convention in Jest?

Ans: Test files typically end with:

.test.js or .spec.js

Example:

Button.test.js or App.spec.js

Ques 8: What is React Testing Library (RTL)?

Ans: RTL is a library for testing React components based on user behavior rather than implementation details. It focuses on how components render and respond to user interactions.

Ques 9: What are the main principles of React Testing Library?

  1. Test behavior, not implementation.
  2. Simulate how a user interacts with the UI.
  3. Avoid testing internal state or private methods.

Ques 10: How do you render a component in RTL?

import { render } from '@testing-library/react';
import MyComponent from './MyComponent';

test('renders correctly', () => {
  render(<MyComponent />);
});

Ques 11: How do you find elements in React Testing Library?

Ans: RTL provides query methods such as:

  • getByText()
  • getByRole()
  • getByLabelText()
  • getByTestId()

Example:

screen.getByText('Submit');

Ques 12: How do you simulate user interactions in RTL?

Ans: Use user-event or fireEvent:

import userEvent from '@testing-library/user-event';

userEvent.click(screen.getByText('Submit'));

Ques 13: What is snapshot testing in React?

Ans: Snapshot testing saves a rendered component’s output in a file and compares it during future test runs to detect unintended UI changes.

import renderer from 'react-test-renderer';
const tree = renderer.create(<Button />).toJSON();
expect(tree).toMatchSnapshot();

Ques 14: When should you use snapshot testing?

Ans: Use it for static components or UI elements that change rarely — such as headers, buttons, or static layouts.

Ques 15: What are mocks in Jest?

Ans: Mocks simulate external dependencies or functions during testing, allowing you to test logic without real API calls.

jest.mock('./api');

Ques 16: What is the difference between mocking and spying?

ConceptDescription
MockingReplaces the real implementation with a fake one
SpyingObserves how a function is used without replacing it

Ques 17: How do you mock API calls in Jest?

global.fetch = jest.fn(() =>
  Promise.resolve({ json: () => Promise.resolve({ data: 'mock' }) })
);

Ques 18: What is asynchronous testing in React?

Ans: Asynchronous testing handles delayed operations such as API calls, timers, or async functions. Use async/await and findBy... methods in RTL.

Example:

const data = await screen.findByText(/loaded/i);

Ques 19: What is waitFor in RTL?

Ans: waitFor waits for an asynchronous action (like state update or API fetch) before running assertions.

await waitFor(() => expect(screen.getByText('Done')).toBeInTheDocument());

Ques 20: How does Jest handle timers?

Ans: Jest provides fake timers for testing setTimeout and setInterval:

jest.useFakeTimers();
jest.advanceTimersByTime(2000);

Ques 21: What are E2E tests in React?

Ans: End-to-End (E2E) tests simulate real user workflows in the browser — clicking buttons, filling forms, navigating pages.

Tools: Cypress, Playwright, Puppeteer

Ques 22: What is Cypress?

Ans: Cypress is an end-to-end testing framework that runs directly in the browser, allowing you to test the full React app in a real environment.

Ques 23: Example of Cypress test:

describe('Login Page', () => {
  it('should log in successfully', () => {
    cy.visit('/login');
    cy.get('input[name="email"]').type('[email protected]');
    cy.get('input[name="password"]').type('12345');
    cy.get('button').click();
    cy.url().should('include', '/dashboard');
  });
});

Ques 24: What is test coverage in Jest?

Ans: Test coverage shows how much of your codebase is covered by tests (functions, statements, branches).

Command:

npm test -- --coverage

Ques 25: How can you improve test coverage?

  • Write tests for edge cases
  • Test all branches of conditions
  • Include async and error-handling scenarios
  • Cover both UI and logic functions

Ques 26: What is Continuous Integration (CI) testing?

Ans: CI testing automatically runs your test suite on every push or pull request (using tools like GitHub Actions, Travis CI, Jenkins) to prevent broken builds.

Ques 27: What’s the difference between unit and E2E tests?

FeatureUnit TestE2E Test
ScopeTests small piecesTests full app flow
SpeedFastSlow
ToolJest, RTLCypress, Playwright
PurposeValidate logicValidate user behavior

Ques 28: What is TDD (Test-Driven Development)?

Ans: TDD is a software development approach where tests are written before the actual code.

Steps:

  1. Write a failing test
  2. Write minimal code to pass it
  3. Refactor and repeat

Ques 29: What is the purpose of test IDs?

Ans: data-testid helps identify elements in tests when they have no accessible role or text.

Example:

<div data-testid="user-profile"></div>

Ques 30: What are some best practices for testing React apps?

  • Test behavior, not implementation
  • Keep tests isolated
  • Avoid using act() manually if not required
  • Mock external dependencies
  • Keep test files near components
  • Run tests automatically on CI

Article 0 of 0