Common Testing Questions
Common Testing Questions
Q: What is the testing pyramid?
The testing pyramid is a model for distributing test types:
- Unit tests (70%): Fast, isolated, test individual functions
- Integration tests (20%): Test component interactions, API integrations
- E2E tests (10%): Slow, expensive, test complete user journeys
Q: Why test from user's perspective?
React Testing Library tests from user perspective because:
- Tests are more robust to implementation changes
- Tests validate actual user behavior
- Tests serve as documentation
- Tests catch accessibility issues
Q: What is test isolation?
Each test should be independent:
- No shared state between tests
- Clean up after each test
- Mock external dependencies
- Use beforeEach/afterEach for setup/cleanup
Q: How do you test error boundaries?
describe('ErrorBoundary', () => {
it('should catch errors', () => {
const ErrorComponent = () => { throw new Error('Test error'); };
render(
<ErrorBoundary>
<ErrorComponent />
</ErrorBoundary>
);
expect(screen.getByText('Something went wrong')).toBeInTheDocument();
});
});
Debugging Tests
Debugging Tests
Common Issues
- Element not found
// Wrong: Using getBy when element doesn't exist yet
const element = screen.getByText('Loading');
// Correct: Use findBy for async
const element = await screen.findByText('Loaded');
// Correct: Use queryByText to check absence
const element = screen.queryByText('Loading');
expect(element).not.toBeInTheDocument();
- Async issues
// Wrong: Not waiting for async
render(<AsyncComponent />);
expect(screen.getByText('Done')).toBeInTheDocument();
// Correct: Wait for assertion
render(<AsyncComponent />);
await waitFor(() => {
expect(screen.getByText('Done')).toBeInTheDocument();
});
- Mock not working
// Wrong: Mocking after import
import { fetchData } from './api';
jest.mock('./api');
// Correct: Mock before import
jest.mock('./api');
import { fetchData } from './api';
Debugging Tools
// screen.debug() - print DOM
render(<MyComponent />);
screen.debug();
// screen.debug(element) - print specific element
const button = screen.getByRole('button');
screen.debug(button);
// logRoles - show accessible roles
import { logRoles } from '@testing-library/dom';
const { container } = render(<MyComponent />);
logRoles(container);
Testing Library Queries
// Check what's in the DOM
screen.logTestingPlaygroundURL();
// Or use the browser extension
// Testing Playground Chrome Extension
Test Coverage
Test Coverage
Coverage Metrics
- Statement coverage: % of statements executed
- Branch coverage: % of branches (if/else) taken
- Function coverage: % of functions called
- Line coverage: % of lines executed
Jest Coverage Config
// jest.config.js
module.exports = {
collectCoverageFrom: [
'src/**/*.{js,jsx,ts,tsx}',
'!src/**/*.d.ts',
'!src/index.tsx',
'!src/reportWebVitals.ts',
],
coverageThreshold: {
global: {
branches: 80,
functions: 80,
lines: 80,
statements: 80,
},
},
};
Running with Coverage
jest --coverage
# Or in package.json
{
"scripts": {
"test:coverage": "jest --coverage --coverageReporters=text-lcov"
}
}
Coverage Reports
// HTML report
jest --coverage --coverageReporters=html
// LCOV for CI
jest --coverage --coverageReporters=lcov
// Text for terminal
jest --coverage --coverageReporters=text
What Coverage Doesn't Tell You
- Missing tests: Code without tests
- Missing assertions: Tests that don't assert
- Missing edge cases: Not all paths tested
- Missing error handling: Error paths not tested
Good Coverage Targets
| Metric | Target |
|---|---|
| Statements | 80%+ |
| Branches | 75%+ |
| Functions | 80%+ |
| Lines | 80%+ |
Anti-Patterns
- Chasing 100% coverage: Diminishing returns
- Testing implementation details: Tests break when code changes
- Ignoring flaky tests: Fix or delete them
- Not testing error paths: Errors happen in production
Practice Problems
Create a reusable React component implementing Testing Interview. Include proper state management and accessibility.
Solution
// Production-ready component with:
// - Proper TypeScript types
// - Accessibility (ARIA)
// - Error boundaries
// - Loading states
// - Memoization where neededWrite unit and integration tests for Testing Interview using React Testing Library.
Solution
// Test coverage:
// 1. Rendering tests
// 2. Interaction tests
// 3. Edge case tests
// 4. Accessibility testsOptimize Testing Interview for performance. Consider memoization, code splitting, and bundle size.
Solution
// Optimization techniques:
// 1. React.memo / useMemo / useCallback
// 2. Code splitting with lazy()
// 3. Virtual scrolling for lists
// 4. Image lazy loading
// 5. Bundle analysisQuiz
1. What should you do when a test is flaky?
2. Why is 100% test coverage not recommended?
3. What is the primary purpose of Testing Interview?
4. What is a common mistake when implementing Testing Interview?
Flashcards
Question
What is the testing pyramid?
Click to reveal answer
Answer
A model suggesting 70% unit, 20% integration, 10% E2E tests.
Question
Why test from user's perspective?
Click to reveal answer
Answer
Tests are more robust, validate actual behavior, and catch accessibility issues.
Question
What is test isolation?
Click to reveal answer
Answer
Each test is independent with no shared state, using setup/teardown for cleanup.
Question
What is good test coverage?
Click to reveal answer
Answer
80%+ for statements, branches, functions, and lines as a target.
Question
What is Testing Interview?
Click to reveal answer
Answer
Testing Interview is a key concept in frontend development.
Revision Notes
Key Takeaways
- 1.Testing pyramid balances speed and confidence
- 2.Test from user's perspective for robustness
- 3.Test isolation ensures reliable tests
- 4.80%+ coverage is a good target
- 5.Flaky tests should be fixed or deleted
Interview Tips
- •Explain the testing pyramid and why it's important
- •Discuss test isolation and how to achieve it
- •Know common testing patterns and anti-patterns
Cheat Sheet
Testing Interview Cheat Sheet
Testing Pyramid
- 70% Unit
- 20% Integration
- 10% E2E
Key Concepts
- Test isolation
- User perspective
- Coverage metrics
- Debugging tools
Common Issues
- Flaky tests
- Async handling
- Mocking
- Coverage goals
Tools
- React Testing Library
- Jest
- MSW
- Cypress/Playwright