42. Testing (Unit & Component)
Ensuring Reliability
When you are maintaining production platforms, you cannot afford to have a new feature break an old one silently. Automated tests act as a safety net. They are scripts that run your code and verify it behaves exactly as expected before you deploy it to the public.
Types of Tests
Unit Tests: Test a single, isolated function (e.g., a utility function that formats currency).
Component Tests: Render a specific React component in memory and interact with it (e.g., clicking a button to ensure a modal opens).
End-to-End (E2E) Tests: Spin up a real browser and simulate a user clicking through the entire application flow.
Jest vs React Testing Library (RTL)
These two tools work together. Jest is the test runner. It executes the files and provides the assertion methods (expect(x).toBe(y)). React Testing Library provides tools to render your components in a fake DOM and interact with them like a real user.
Testing Components (The AAA Pattern)
When writing component tests, always use the AAA pattern: Arrange (set up the component), Act (simulate user interaction), Assert (verify the UI updated correctly).
Mocking APIs
Automated tests must be fast and deterministic. You should never make real API calls to an external server during a test. If the server is down, your frontend test will fail, which is a false negative. Instead, you "mock" the API to instantly return fake data.
Knowledge Check
Ready to test your understanding of 42. Testing (Unit & Component)?