๐งช
Intermediate
6 min readTesting & Debugging
Unit testing, integration testing, and debugging techniques
Testing & Debugging Interview Questions
Master testing frameworks and debugging techniques for frontend applications.
1. Jest - Unit Testing
// Basic test
test('adds 1 + 2 to equal 3', () => {
expect(1 + 2).toBe(3);
});
describe('Calculator', () => {
test('adds numbers', () => {
expect(add(2, 3)).toBe(5);
});
test('multiplies numbers', () => {
expect(multiply(2, 3)).toBe(6);
});
});
// Matchers
expect(value).toBe(5);
expect(value).toEqual({ name: 'John' });
expect(value).toBeTruthy();
expect(array).toContain('item');
expect(fn).toThrow();
// Async testing
test('fetches data', async () => {
const data = await fetchData();
expect(data).toEqual({ id: 1 });
});
// Mocking
jest.mock('./api');
const mockFetch = jest.fn(() => Promise.resolve({ data: 'test' }));
2. React Testing Library
import { render, screen, fireEvent } from '@testing-library/react';
import '@testing-library/jest-dom';
test('renders button', () => {
render(<Button label="Click me" />);
const button = screen.getByText('Click me');
expect(button).toBeInTheDocument();
});
test('handles click', () => {
const handleClick = jest.fn();
render(<Button onClick={handleClick} />);
fireEvent.click(screen.getByRole('button'));
expect(handleClick).toHaveBeenCalledTimes(1);
});
test('shows loading state', async () => {
render(<UserList />);
expect(screen.getByText('Loading...')).toBeInTheDocument();
await waitFor(() => {
expect(screen.getByText('John')).toBeInTheDocument();
});
});
3. Debugging Techniques
// Console methods
console.log('Basic log');
console.error('Error message');
console.warn('Warning');
console.table([{ name: 'John' }, { name: 'Jane' }]);
console.time('timer');
console.timeEnd('timer');
// Debugger
function buggyFunction() {
debugger; // Pauses execution
const result = complexCalculation();
return result;
}
// Chrome DevTools
// Sources tab: Set breakpoints, step through code
// Network tab: Monitor requests
// Performance tab: Identify bottlenecks
Key Takeaways:
- Write unit tests for pure functions
- Test user interactions with Testing Library
- Mock external dependencies
- Use debugger and console effectively
- Test edge cases and error states