Testing has become one of the most crucial skills for modern React developers. Companies don’t just want you to build components they want you to write reliable tests, ensure accessibility, and prevent regressions.
Whether you’re a fresher learning the basics, or preparing for a FAANG-level React interview, you’ll likely face React testing interview questions.
This guide gives you 60+ powerful React testing interview questions with answers (2025 edition). It covers:
- Fundamentals (Jest, RTL basics, unit testing)
- Intermediate concepts (async testing, mocking, context, Redux, routers)
- Advanced testing (RSC, SSR, Next.js, CI/CD, accessibility, performance)
By the end, you’ll be ready to handle any React testing interview.
Table of Contents
Beginner React Testing Interview Questions (Freshers / Junior Devs)
Why do we test React applications?
Answer:
Testing ensures React apps behave as expected, helps prevent regressions, and builds confidence when shipping new features. It reduces reliance on manual QA and speeds up development.
Example: A simple test verifying that a heading is rendered.
import { render, screen } from '@testing-library/react';
import App from './App';
test('renders app heading', () => {
render(<App />);
expect(screen.getByRole('heading', { name: /my react app/i })).toBeInTheDocument();
});
What types of tests are common in React?
Answer:
- Unit tests → Verify small isolated pieces like functions or hooks.
- Integration tests → Ensure multiple components work together.
- End-to-end (E2E) tests → Test full user flows (usually with Cypress or Playwright).
Example: Unit test for a utility function.
function add(a, b) {
return a + b;
}
test('adds numbers correctly', () => {
expect(add(2, 3)).toBe(5);
});
What is Jest and why is it used with React?
Answer:
Jest is the most popular JavaScript testing framework for React. It provides:
- A test runner
- Assertions (
expect
) - Mocks
- Snapshot testing
- Coverage reports
Example: Simple Jest test.
test('truthy values', () => {
expect(true).toBeTruthy();
expect(false).toBeFalsy();
});
What is React Testing Library (RTL)?
Answer:
React Testing Library focuses on testing user behavior rather than implementation details. It encourages testing components as a user would interact with them (via roles, labels, text).
Example: Testing a button click with RTL.
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
function Button({ onClick }) {
return <button onClick={onClick}>Click Me</button>;
}
test('calls onClick when button is clicked', async () => {
const handleClick = jest.fn();
render(<Button onClick={handleClick} />);
await userEvent.click(screen.getByRole('button', { name: /click me/i }));
expect(handleClick).toHaveBeenCalledTimes(1);
});
How is RTL different from Enzyme?
Answer:
- RTL → Tests behavior (how users interact with components).
- Enzyme → Tests implementation details (state, props, lifecycle).
Enzyme is mostly deprecated, while RTL is the modern standard.
What does “testing behavior, not implementation” mean?
Answer:
Instead of testing component internals (like state), test what the user sees and interacts with.
Bad (implementation detail):
expect(wrapper.state('count')).toBe(1);
Good (behavior):
expect(screen.getByText(/count: 1/i)).toBeInTheDocument();
What are the differences between getBy
, queryBy
, and findBy
?
Answer:
getBy*
→ Sync, throws if not found.queryBy*
→ Sync, returnsnull
if not found (use for absence checks).findBy*
→ Async, returns a promise (use for async elements).
Example:
expect(screen.getByText(/hello/i)).toBeInTheDocument();
expect(screen.queryByText(/does not exist/i)).toBeNull();
expect(await screen.findByText(/loaded data/i)).toBeInTheDocument();
Why prefer getByRole
over getByTestId
?
Answer:
getByRole
→ Accessible, user-centric, resilient.getByTestId
→ Useful fallback but not recommended as default.
Example:
expect(screen.getByRole('button', { name: /submit/i })).toBeInTheDocument();
What is the purpose of screen
in RTL?
Answer:
screen
is a global query object. It avoids destructuring queries from render()
and improves readability.
Example:
render(<button>Save</button>);
expect(screen.getByRole('button', { name: /save/i })).toBeInTheDocument();
Difference between fireEvent
and user-event
?
Answer:
fireEvent
→ Low-level DOM events.user-event
→ Higher-level interactions (typing, clicking, tabbing).
Example:
await userEvent.type(screen.getByRole('textbox'), 'Hello');
expect(screen.getByRole('textbox')).toHaveValue('Hello');
How do you test a button click in RTL?
Example:
function Counter() {
const [count, setCount] = React.useState(0);
return (
<>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</>
);
}
test('increments count on click', async () => {
render(<Counter />);
await userEvent.click(screen.getByRole('button', { name: /increment/i }));
expect(screen.getByText(/count: 1/i)).toBeInTheDocument();
});
How do you test form inputs in RTL?
Example:
function Form() {
const [value, setValue] = React.useState('');
return <input value={value} onChange={(e) => setValue(e.target.value)} />;
}
test('updates input value', async () => {
render(<Form />);
const input = screen.getByRole('textbox');
await userEvent.type(input, 'React');
expect(input).toHaveValue('React');
});
How do you test conditional rendering?
Example:
function Greeting({ isLoggedIn }) {
return <div>{isLoggedIn ? 'Welcome back!' : 'Please log in'}</div>;
}
test('renders different text based on props', () => {
render(<Greeting isLoggedIn={false} />);
expect(screen.getByText(/please log in/i)).toBeInTheDocument();
render(<Greeting isLoggedIn={true} />);
expect(screen.getByText(/welcome back/i)).toBeInTheDocument();
});
What are snapshot tests in React?
Answer:
Snapshot tests capture a component’s output and compare it on future runs to detect unexpected UI changes.
Example:
import renderer from 'react-test-renderer';
import Greeting from './Greeting';
test('matches snapshot', () => {
const tree = renderer.create(<Greeting isLoggedIn={true} />).toJSON();
expect(tree).toMatchSnapshot();
});
How do you run React tests?
Answer:
- Most React projects use Jest by default.
- Run
npm test
oryarn test
. - Jest automatically looks for files with
.test.js
or.spec.js
.
Intermediate React Testing Interview Questions (Mid-Level Devs)
How do you test async code in React?
Answer:
For async UI (like data fetching), you should:
- Use
findBy*
queries for awaiting elements. - Use
waitFor
to wait for state changes.
Example:
import { render, screen, waitFor } from '@testing-library/react';
function AsyncMessage() {
const [msg, setMsg] = React.useState('');
React.useEffect(() => {
setTimeout(() => setMsg('Hello World'), 500);
}, []);
return <div>{msg || 'Loading...'}</div>;
}
test('renders async message', async () => {
render(<AsyncMessage />);
expect(screen.getByText(/loading/i)).toBeInTheDocument();
expect(await screen.findByText(/hello world/i)).toBeInTheDocument();
});
How do you mock API calls in tests?
Answer:
Use jest.fn()
or jest.mock()
for API modules, or MSW (Mock Service Worker) for realistic mocks.
Example: Mocking fetch
:
global.fetch = jest.fn(() =>
Promise.resolve({ json: () => Promise.resolve({ data: 'Hello' }) })
);
function FetchComponent() {
const [data, setData] = React.useState(null);
React.useEffect(() => {
fetch('/api').then(res => res.json()).then(setData);
}, []);
return <div>{data ? data.data : 'Loading'}</div>;
}
test('fetches and displays data', async () => {
render(<FetchComponent />);
expect(await screen.findByText(/hello/i)).toBeInTheDocument();
});
How do you test components that use Context API?
Answer:
Wrap your component with the relevant context provider in tests.
Example:
const UserContext = React.createContext();
function UserProfile() {
const user = React.useContext(UserContext);
return <div>{user ? `Hello, ${user.name}` : 'Guest'}</div>;
}
test('renders user from context', () => {
render(
<UserContext.Provider value={{ name: 'Alice' }}>
<UserProfile />
</UserContext.Provider>
);
expect(screen.getByText(/hello, alice/i)).toBeInTheDocument();
});
How do you test components that use Redux?
Answer:
Wrap components in <Provider store={store}>
during tests.
Example:
import { Provider } from 'react-redux';
import { configureStore, createSlice } from '@reduxjs/toolkit';
const slice = createSlice({
name: 'counter',
initialState: { value: 0 },
reducers: { increment: (state) => { state.value += 1; } },
});
const store = configureStore({ reducer: { counter: slice.reducer } });
function Counter() {
const value = store.getState().counter.value;
return <div>Count: {value}</div>;
}
test('renders redux state', () => {
render(
<Provider store={store}>
<Counter />
</Provider>
);
expect(screen.getByText(/count: 0/i)).toBeInTheDocument();
});
How do you test components that use React Router?
Answer:
Use MemoryRouter
from react-router-dom
to simulate navigation.
Example:
import { MemoryRouter, Route, Routes } from 'react-router-dom';
function Home() { return <div>Home Page</div>; }
function About() { return <div>About Page</div>; }
test('navigates between routes', () => {
render(
<MemoryRouter initialEntries={['/about']}>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</MemoryRouter>
);
expect(screen.getByText(/about page/i)).toBeInTheDocument();
});
How do you test custom hooks in React?
Answer:
Use renderHook
from @testing-library/react-hooks
(or new @testing-library/react
utilities).
Example:
import { renderHook, act } from '@testing-library/react';
function useCounter() {
const [count, setCount] = React.useState(0);
return { count, increment: () => setCount(c => c + 1) };
}
test('increments counter', () => {
const { result } = renderHook(() => useCounter());
act(() => { result.current.increment(); });
expect(result.current.count).toBe(1);
});
How do you test components with async data fetching?
Answer:
Check initial loading state and then final rendered result.
Example:
function DataComponent() {
const [data, setData] = React.useState(null);
React.useEffect(() => {
fetch('/api/data').then(res => res.json()).then(setData);
}, []);
return data ? <div>{data.message}</div> : <div>Loading...</div>;
}
test('displays loading then data', async () => {
global.fetch = jest.fn(() =>
Promise.resolve({ json: () => Promise.resolve({ message: 'Hi' }) })
);
render(<DataComponent />);
expect(screen.getByText(/loading/i)).toBeInTheDocument();
expect(await screen.findByText(/hi/i)).toBeInTheDocument();
});
How do you test accessibility in React apps?
Answer:
Prefer queries like getByRole
, getByLabelText
. Optionally integrate jest-axe
for automated a11y tests.
Example:
import { axe, toHaveNoViolations } from 'jest-axe';
expect.extend(toHaveNoViolations);
function Form() {
return (
<form>
<label htmlFor="name">Name</label>
<input id="name" />
</form>
);
}
test('has no accessibility violations', async () => {
const { container } = render(<Form />);
expect(await axe(container)).toHaveNoViolations();
});
How do you test components with side effects (useEffect
)?
Example:
function Timer({ onTick }) {
React.useEffect(() => {
const id = setInterval(onTick, 1000);
return () => clearInterval(id);
}, [onTick]);
return <div>Timer Running</div>;
}
test('calls onTick periodically', () => {
jest.useFakeTimers();
const mockFn = jest.fn();
render(<Timer onTick={mockFn} />);
jest.advanceTimersByTime(3000);
expect(mockFn).toHaveBeenCalledTimes(3);
});
What causes “not wrapped in act(…)” warnings?
Answer:
React warns when state updates aren’t properly handled. RTL usually wraps updates in act()
, but async updates may require waitFor
.
Fix with waitFor
:
await waitFor(() => expect(screen.getByText(/done/i)).toBeInTheDocument());
How do you test portals like modals or tooltips?
Example:
function Modal({ isOpen }) {
return isOpen ? ReactDOM.createPortal(<div>Modal Content</div>, document.body) : null;
}
test('renders modal via portal', () => {
render(<Modal isOpen={true} />);
expect(screen.getByText(/modal content/i)).toBeInTheDocument();
});
How do you test timers (setTimeout, setInterval)?
Example:
function DelayedMessage() {
const [msg, setMsg] = React.useState('');
React.useEffect(() => {
setTimeout(() => setMsg('Hello after 1s'), 1000);
}, []);
return <div>{msg}</div>;
}
test('delayed message', () => {
jest.useFakeTimers();
render(<DelayedMessage />);
jest.advanceTimersByTime(1000);
expect(screen.getByText(/hello after 1s/i)).toBeInTheDocument();
});
How do you test lazy-loaded components?
Example:
const LazyComp = React.lazy(() => Promise.resolve({ default: () => <div>Lazy Loaded</div> }));
test('renders lazy component', async () => {
render(
<React.Suspense fallback={<div>Loading...</div>}>
<LazyComp />
</React.Suspense>
);
expect(screen.getByText(/loading/i)).toBeInTheDocument();
expect(await screen.findByText(/lazy loaded/i)).toBeInTheDocument();
});
How do you test drag-and-drop functionality?
Example (simplified):
function Draggable() {
return <div draggable data-testid="drag">Drag Me</div>;
}
test('drag and drop', () => {
const drag = screen.getByTestId('drag');
fireEvent.dragStart(drag);
expect(drag).toBeInTheDocument();
});
How do you test components with refs (useRef
)?
Answer:
Refs are implementation details. Test the effect of the ref, not the ref itself.
Example:
function FocusInput() {
const ref = React.useRef();
return <input ref={ref} placeholder="Name" />;
}
test('renders input with ref', () => {
render(<FocusInput />);
expect(screen.getByPlaceholderText(/name/i)).toBeInTheDocument();
});
Advanced React Testing Interview Questions (Senior / FAANG-Level)
How do you structure tests in large-scale React apps?
Answer:
- Organize by feature/module, not by test type.
- Keep tests close to components (
Button.test.js
). - Use helpers for repeated setup (e.g., custom
render
). - Balance unit, integration, and E2E tests.
Example of a custom render helper for providers:
import { render } from '@testing-library/react';
import { Provider } from 'react-redux';
import store from './store';
const customRender = (ui, options) =>
render(<Provider store={store}>{ui}</Provider>, options);
export * from '@testing-library/react';
export { customRender as render };
How do you test authentication flows?
Answer:
Mock authentication providers (Auth0, Firebase, NextAuth) and test logged-in vs logged-out scenarios.
Example:
function Dashboard({ user }) {
return <div>{user ? `Welcome, ${user.name}` : 'Please log in'}</div>;
}
test('shows dashboard for logged-in user', () => {
render(<Dashboard user={{ name: 'Alice' }} />);
expect(screen.getByText(/welcome, alice/i)).toBeInTheDocument();
});
How do you test role-based access control (RBAC)?
Answer:
Render with different mocked roles and check allowed/restricted content.
Example:
function AdminPanel({ role }) {
return role === 'admin' ? <div>Secret Settings</div> : <div>Access Denied</div>;
}
test('admin sees settings, user denied', () => {
render(<AdminPanel role="admin" />);
expect(screen.getByText(/secret settings/i)).toBeInTheDocument();
render(<AdminPanel role="user" />);
expect(screen.getByText(/access denied/i)).toBeInTheDocument();
});
How do you test GraphQL requests in React apps?
Answer:
Use Apollo’s MockedProvider
or MSW for GraphQL mocks.
✅ Example (Apollo):
import { MockedProvider } from '@apollo/client/testing';
import { gql } from '@apollo/client';
const GET_USER = gql`{ user { name } }`;
function User({ data }) {
return <div>{data?.user?.name || 'Loading'}</div>;
}
test('renders GraphQL user', async () => {
render(
<MockedProvider mocks={[{ request: { query: GET_USER }, result: { data: { user: { name: 'Alice' } } } }]}>
<User />
</MockedProvider>
);
expect(await screen.findByText(/alice/i)).toBeInTheDocument();
});
How do you test WebSockets or real-time features?
Answer:
Mock the socket server and simulate messages.
Example (pseudo):
const socket = { on: jest.fn(), emit: jest.fn() };
test('handles socket message', () => {
socket.on.mockImplementation((event, cb) => {
if (event === 'message') cb('Hello');
});
// assert UI updated
});
How do you test Next.js components?
Answer:
- Use
@testing-library/react
for client components. - Mock Next.js router with
next/router
.
Example:
jest.mock('next/router', () => ({
useRouter: () => ({ pathname: '/about' }),
}));
function Page() {
const { pathname } = require('next/router').useRouter();
return <div>Path: {pathname}</div>;
}
test('renders next.js route', () => {
render(<Page />);
expect(screen.getByText(/path: \/about/i)).toBeInTheDocument();
});
How do you test React Server Components (RSC)?
Answer:
Since RSCs run server-side, test at the integration boundary (server render + hydration).
Example:
import { renderToString } from 'react-dom/server';
import App from './App.server';
test('renders RSC', () => {
const html = renderToString(<App />);
expect(html).toContain('Hello from server');
});
How do you test error boundaries?
Example:
class ErrorBoundary extends React.Component {
state = { hasError: false };
static getDerivedStateFromError() { return { hasError: true }; }
render() { return this.state.hasError ? 'Error!' : this.props.children; }
}
function Buggy() { throw new Error('Crash!'); }
test('renders error fallback', () => {
render(<ErrorBoundary><Buggy /></ErrorBoundary>);
expect(screen.getByText(/error/i)).toBeInTheDocument();
});
How do you test performance-heavy components?
Answer:
- Measure renders with React DevTools profiler.
- In tests, assert memoization (
React.memo
,useMemo
).
Example:
const Expensive = React.memo(({ value }) => <div>{value}</div>);
How do you test Suspense for data fetching?
Example:
const LazyComp = React.lazy(() => Promise.resolve({ default: () => <div>Loaded</div> }));
test('handles suspense', async () => {
render(
<React.Suspense fallback={<div>Loading...</div>}>
<LazyComp />
</React.Suspense>
);
expect(screen.getByText(/loading/i)).toBeInTheDocument();
expect(await screen.findByText(/loaded/i)).toBeInTheDocument();
});
How do you prevent flaky tests?
- Avoid arbitrary
setTimeout
. - Use
findBy*
orwaitFor
. - Mock consistently.
- Clean up timers/events.
How do you integrate React tests into CI/CD pipelines?
- Run
npm test -- --coverage
. - Fail builds on low coverage.
- Parallelize E2E + unit tests.
How do you measure test coverage?
Example: Run in CLI:
npm test -- --coverage
Generates a report (statements, branches, functions, lines).
How do you balance unit vs integration vs E2E tests?
- Testing Pyramid → many unit, fewer integration, fewer E2E.
- Testing Trophy → favor integration + E2E, fewer unit.
Companies may ask which you’d pick — both are valid depending on app scale.
How do you test components using third-party libraries (charts, maps)?
Answer:
- Mock heavy libs.
- Assert wrapper/container presence.
Example:
jest.mock('chart.js', () => ({ Chart: () => null }));
How do you test file uploads?
Example:
function FileUploader() {
return <input type="file" />;
}
test('uploads file', async () => {
render(<FileUploader />);
const file = new File(['hello'], 'hello.png', { type: 'image/png' });
const input = screen.getByLabelText(/file/i);
await userEvent.upload(input, file);
expect(input.files[0]).toBe(file);
});
How do you test accessibility keyboard navigation?
Example:
test('navigates with keyboard', async () => {
render(<><button>One</button><button>Two</button></>);
await userEvent.tab();
expect(screen.getByText(/one/i)).toHaveFocus();
await userEvent.tab();
expect(screen.getByText(/two/i)).toHaveFocus();
});
How do you handle flaky async tests in CI?
- Use
waitFor
. - Retry failed selectors.
- Mock stable network.
How do you test server-side rendering (SSR)?
Example:
import { renderToString } from 'react-dom/server';
test('SSR renders markup', () => {
const html = renderToString(<div>Hello</div>);
expect(html).toContain('Hello');
});
How do you test monorepos with shared React components?
- Configure Jest in workspaces.
- Use
moduleNameMapper
for aliases. - Ensure each package has isolated tests.
How do you write maintainable test suites?
- Independent tests.
- Descriptive test names.
- Avoid over-mocking.
- Use custom utilities.
How do you debug failing tests in CI?
- Run locally with
--runInBand
. - Add
console.log
orscreen.debug()
. - Use
--detectOpenHandles
for async leaks.
What are common mistakes in React testing?
- Testing implementation details.
- Overusing snapshots.
- Not cleaning up mocks.
- Ignoring accessibility roles.
How do you test advanced hooks (useReducer
, useMemo
, useCallback
)?
Example:
function Counter() {
const [count, dispatch] = React.useReducer((s, a) => s + a, 0);
return <>
<div>Count: {count}</div>
<button onClick={() => dispatch(1)}>+</button>
</>;
}
How do you test analytics or tracking events?
Example:
const track = jest.fn();
function Button() {
return <button onClick={() => track('clicked')}>Click</button>;
}
test('sends analytics event', async () => {
render(<Button />);
await userEvent.click(screen.getByRole('button'));
expect(track).toHaveBeenCalledWith('clicked');
});
How do you test forms with validation libraries?
Example (React Hook Form):
import { useForm } from 'react-hook-form';
function Form() {
const { register, handleSubmit, formState } = useForm();
return (
<form onSubmit={handleSubmit(() => {})}>
<input {...register('name', { required: true })} />
{formState.errors.name && <span>Name required</span>}
<button type="submit">Submit</button>
</form>
);
}
How do you test applications with feature flags?
Example:
function Feature({ enabled }) {
return enabled ? <div>Feature On</div> : <div>Feature Off</div>;
}
How do you test infinite scrolling or pagination?
Example:
fireEvent.scroll(window, { target: { scrollY: 1000 } });
How do you test internationalization (i18n)?
Example:
const messages = { en: 'Hello', fr: 'Bonjour' };
function Greeting({ lang }) { return <div>{messages[lang]}</div>; }
test('renders french greeting', () => {
render(<Greeting lang="fr" />);
expect(screen.getByText(/bonjour/i)).toBeInTheDocument();
});
What testing challenges are unique to React in 2025?
- React Server Components → server + client boundaries.
- Streaming UIs → async hydration.
- Real-time apps → websockets/signals.
- New tooling → adoption of Vitest alongside Jest.
Most Common React Testing Interview Mistakes
Even strong candidates sometimes trip up when answering React Testing Interview Questions. Here are the most common mistakes to avoid:
- Testing implementation details instead of behavior
- ❌ Example: Checking
state
directly or spying on private methods. - ✅ Fix: Test what the user sees and does (
screen.getByRole
,userEvent.click
).
- ❌ Example: Checking
- Overusing snapshot tests
- Snapshots quickly become brittle. Interviewers expect you to know that they should only be used for stable UI components.
- Ignoring accessibility in tests
- Using
getByTestId
everywhere signals poor testing habits. - ✅ Instead: Prefer
getByRole
,getByLabelText
,getByPlaceholderText
.
- Using
- Flaky async tests
- ❌ Using
setTimeout
in tests or checking DOM before async tasks complete. - ✅ Fix: Use
findBy*
orwaitFor
.
- ❌ Using
- Not cleaning up mocks or timers
- ❌ Forgetting
jest.clearAllMocks()
orjest.useRealTimers()
. - Leads to inter-test pollution.
- ❌ Forgetting
Pro Tip: If an interviewer asks, “What’s the biggest mistake you’ve seen in React testing?”, mention one of the above and explain how you’d avoid it.
React Testing Best Practices for Interviews
When tackling React Testing Interview Questions, highlight these best practices:
- Test behavior, not implementation
- Example: Instead of checking prop values, simulate user clicks and assert changes in DOM.
- Prefer
user-event
overfireEvent
user-event
better simulates real user interactions (typing, tabbing, clicks).
- Use semantic queries first
getByRole
>getByLabelText
>getByPlaceholderText
>getByTestId
.
- Mock APIs with MSW (Mock Service Worker)
- More reliable than manually mocking
fetch
or Axios. - Shows interviewers you understand realistic test environments.
- More reliable than manually mocking
- Handle async code with
findBy
andwaitFor
- Example:
expect(await screen.findByText(/welcome/i)).toBeInTheDocument();
- Example:
- Keep tests independent
- Each test should run in isolation — no shared state across tests.
- Follow the testing trophy (Kent C. Dodds)
- Balance: more integration tests, some unit tests, fewer end-to-end tests.
In an interview, when asked about “best practices in React testing,” listing 3-4 of these points shows you’re battle-tested.
React Testing Cheat Sheet (Quick Reference)
Here’s a cheat sheet you can use for both coding interviews and real projects:
Queries Hierarchy (RTL)
- Best:
getByRole
,getByLabelText
,getByText
- Fallbacks:
getByPlaceholderText
,getByDisplayValue
- Last resort:
getByTestId
Async Testing
getBy*
→ synchronous, throws if not foundqueryBy*
→ synchronous, returnsnull
if not foundfindBy*
→ asynchronous, waits for element
expect(screen.queryByText(/error/i)).toBeNull();
expect(await screen.findByText(/success/i)).toBeInTheDocument();
Events
- Use
userEvent
instead offireEvent
:
await userEvent.type(screen.getByRole('textbox'), 'Hello');
await userEvent.click(screen.getByRole('button'));
Timers
jest.useFakeTimers();
jest.advanceTimersByTime(1000);
jest.useRealTimers();
Mocking APIs
- Simple mock:
global.fetch = jest.fn(() =>
Promise.resolve({ json: () => Promise.resolve({ message: 'Hi' }) })
);
- Better: Use MSW for network request mocks.
Cleanup
- After each test:
afterEach(() =>
jest.clearAllMocks());
Key Takeaways
- Most companies use Jest + React Testing Library in 2025.
- Focus on behavior-driven testing, not internals.
- Be comfortable with async flows, mocking, providers, routers, and accessibility.
- Senior interviews (FAANG) go deeper into testing strategy, CI/CD, SSR, and scalability.
Next: Read our 100+ React Interview Questions and Answers (2025) to cover the complete spectrum of React interviews.