Testing Basics
Stop verifying your code by manually clicking around the browser. Learn the foundations of automated unit testing and the Arrange-Act-Assert pattern.
Automated Verification
As your application grows, it becomes impossible to manually test every single feature after every single code change. Automated Testing is the practice of writing code that tests your code.
A **Unit Test** isolates a specific function or component and verifies that it behaves correctly given a set of controlled inputs.
Fearless Refactoring
Without tests, developers are often terrified to change old code for fear of breaking something unrelated. A robust test suite acts as a safety net.
If you rewrite a function to make it faster, and all your tests still pass, you have mathematical proof that you didn't break the application.
Arrange, Act, Assert
Almost all tests follow the AAA pattern:
1. **Arrange:** Set up the test data. 2. **Act:** Call the function being tested. 3. **Assert:** Verify the output matches expectations.
javascript
test('calculates total with tax', () => {
// 1. Arrange
const cart = [10, 20];
const taxRate = 0.1;
// 2. Act
const total = calculateTotal(cart, taxRate);
// 3. Assert
expect(total).toBe(33);
});
The Red-Green Cycle
Examine the testing architecture below. Notice how a broken implementation triggers a loud, specific assertion failure (Red), providing an exact target for the developer to fix and turn the suite Green.
The AAA Pattern & Red-Green Cycle
const b = 2;
return 0;
}
return a + b;
}
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- Automated testing allows you to confidently refactor code without fear of breaking existing features.
- The **AAA Pattern** stands for Arrange (setup), Act (execute), and Assert (verify).
- A **Unit Test** focuses on a small, isolated piece of logic (like a function).
- **TDD (Test-Driven Development)** is a workflow consisting of three stages: Red (failing test), Green (passing test), and Refactor.
- A test must be deterministic. Flaky tests that randomly pass/fail destroy trust in the test suite.
Done with this concept?
Mark it complete to track your progress. No login needed.