React Interview Questions - Testing & Best Practices (121-150)
Master React testing and best practices for FAANG interviews: Jest, React Testing Library, RTL, best practices, and more with practical examples.
Master React testing and best practices for FAANG interviews: Jest, React Testing Library, RTL, best practices, and more with practical examples. This interview-focused guide covers essential react interview questions - testing & best practices (121-150) concepts for technical interviews.
React Interview Questions - Testing & Best Practices (121-150)
Testing ensures your app works as expected, and best practices keep your codebase maintainable!
Question 121: What is Jest?
Jest is a JavaScript testing framework created by Facebook (Meta). It's the standard for testing React apps!
Key Features:
- Zero configuration
- Fast snapshot testing
- Built-in assertions and mocking
Question 122: What is React Testing Library (RTL)?
React Testing Library is a lightweight library that encourages testing components the way users interact with them, not testing implementation details!
Core Philosophy:
"The more your tests resemble the way your software is used, the more confidence they can give you."
Question 123: React Testing Library Example
import { render, screen, fireEvent } from '@testing-library/react';
import LoginForm from './LoginForm';
test('submits login form with email and password', () => {
render(<LoginForm onSubmit={jest.fn()} />);
// Find inputs like a user would
const emailInput = screen.getByLabelText(/email/i);
const passwordInput = screen.getByLabelText(/password/i);
const submitButton = screen.getByText(/login/i);
// Interact like a user
fireEvent.change(emailInput, { target: { value: 'user@example.com' } });
fireEvent.change(passwordInput, { target: { value: 'password123' } });
fireEvent.click(submitButton);
});
Question 124: RTL Query Types
| Query Type | Matches | Use When |
|---|---|---|
getBy* | First match, throws error if not found | Element definitely exists |
findBy* | First match, async (use await) | Element appears after async operation |
queryBy* | First match, returns null if not found | Element might not exist |
Question 125: What is a snapshot test?
Snapshot tests take a "snapshot" of your component's rendered output and compare it to a previous snapshot to ensure it hasn't changed unexpectedly.
Example:
import { render } from '@testing-library/react';
import Button from './Button';
test('button renders correctly', () => {
const { asFragment } = render(<Button>Click Me</Button>);
expect(asFragment()).toMatchSnapshot();
});
Question 126: What is mocking in testing?
Mocking replaces parts of your code with fake implementations. Common uses:
- Mock API calls
- Mock functions
- Mock modules
Question 127: Mocking fetch API
global.fetch = jest.fn(() =>
Promise.resolve({
json: () => Promise.resolve({ data: 'mocked data' }),
})
);
Question 128: What is Test-Driven Development (TDD)?
TDD is a development practice where you write tests before you write the code!
Steps:
- Red: Write a test that fails
- Green: Write minimal code to make the test pass
- Refactor: Clean up the code without breaking tests
Question 129: What are unit tests vs integration tests vs E2E tests?
| Test Type | What it tests | Scope |
|---|---|---|
| Unit Tests | Individual pieces (functions, components) | Small |
| Integration Tests | How multiple pieces work together | Medium |
| E2E Tests | Entire application from start to finish | Large |
Question 130: What is Cypress?
Cypress is a modern E2E testing framework for web apps that runs directly in the browser!
Question 131: React Best Practices: Components
- Keep components small and focused (Single Responsibility Principle)
- Use functional components with hooks
- Give components clear, descriptive names
- Split large components into smaller ones
- Use JSX properly (indentation, tags)
Question 132: React Best Practices: State Management
- Keep state as local as possible
- Lifting state up when needed
- Normalize state shape if using Redux/Zustand
- Avoid prop drilling (use Context API or composition)
Question 133: React Best Practices: Performance
- Avoid unnecessary re-renders
- Virtualize long lists
- Code splitting
- Lazy load components
- Optimize images
Question 134: What is prop-types?
prop-types is a library that checks the types of props at runtime (development only).
Example:
import PropTypes from 'prop-types';
function User({ name, age, isAdmin }) {
return <div>{name}</div>;
}
User.propTypes = {
name: PropTypes.string.isRequired,
age: PropTypes.number,
isAdmin: PropTypes.bool
};
Question 135: What is TypeScript in React?
TypeScript adds static types to JavaScript, catching errors before runtime!
Example:
interface UserProps {
name: string;
age: number;
isAdmin?: boolean;
}
const User: React.FC<UserProps> = ({ name, age, isAdmin }) => {
return <div>{name} is {age} years old</div>;
};
Question 136: What is linting?
Linting is the process of analyzing code for potential errors, bugs, stylistic issues, and suspicious constructs!
Common Tools:
- ESLint
- Prettier (code formatting)
Question 137: What is ESLint?
ESLint is a static code analysis tool that helps you find and fix problems in your JavaScript/TypeScript code.
Question 138: What is a design system in React?
A design system is a collection of reusable UI components, design tokens, and guidelines that help maintain consistency across an app!
Common Components:
- Buttons
- Inputs
- Modals
- Cards
- Navigation
- And more...
Question 139: What is component composition vs inheritance?
React favors composition (building components from other components) over inheritance!
Question 140: What are the different ways to style React components?
- Inline styles
- CSS stylesheets
- CSS Modules
- CSS-in-JS (Styled Components, Emotion)
- Utility-first CSS (Tailwind CSS)
Question 141: Styled Components Example
import styled from 'styled-components';
const Button = styled.button`
background: blue;
color: white;
padding: 10px 20px;
border-radius: 4px;
&:hover {
background: darkblue;
}
`;
function App() {
return <Button>Click me</Button>;
}
Question 142: What is React Router?
React Router is the standard library for handling routing in React apps!
Example:
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import Home from './Home';
import About from './About';
function App() {
return (
<Router>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</Router>
);
}
Question 143: What is Next.js?
Next.js is a React framework for building full-stack web apps!
Key Features:
- File-system routing
- Server-side rendering (SSR)
- Static site generation (SSG)
- API routes
- Image optimization
Question 144: What is Server Side Rendering (SSR)?
Server-side rendering renders React components on the server and sends the generated HTML to the client!
Question 145: What is Static Site Generation (SSG)?
Static site generation generates HTML pages at build time, making the app extremely fast!
Question 146: What is Incremental Static Regeneration (ISR)?
ISR lets you update static pages after you've built your site, without rebuilding the entire app!
Question 147: What is hydration?
Hydration is the process where React attaches event listeners to server-rendered HTML and makes the app interactive!
Question 148: What are accessibility best practices in React?
- Use semantic HTML
- Add alt text to images
- Add labels to form elements
- Ensure good color contrast
- Test with screen readers
Question 149: What are React security best practices?
- Sanitize user input to prevent XSS attacks
- Validate and sanitize all inputs
- Use
dangerouslySetInnerHTMLcarefully - Keep dependencies updated
- Don't store secrets in client-side code
Question 150: What should you know about React for a FAANG interview?
✅ Core concepts (components, props, state, hooks, virtual DOM) ✅ Lifecycle methods (both class and hooks) ✅ Performance optimization ✅ State management (local, Context, Redux, Zustand, etc.) ✅ Testing (Jest, React Testing Library, Cypress) ✅ Best practices (accessibility, security, maintainability) ✅ Frameworks like Next.js