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.

JavaScript7 min readConcept 61 of 63

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

The Test Block
test('calculates the sum', () => {
Arrange
const a = 2;
const b = 2;
Act
const result = sum(a, b);
Assert
expect(result).toBe(4);
});
Stage 1: Red (Failing)
// Broken Implementation
function sum(a, b) {
return 0;
}
AssertionError:
Expected: 4
Received: 0
Stage 2: Green (Fixed)
// Fixed Implementation
function sum(a, b) {
return a + b;
}
1 Passing
iThe Red-Green cycle proves that your test actually works. If you write a test and it immediately passes (Green) before you've even written the implementation, the test is useless.

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1What are the three steps of the AAA testing pattern?
  2. 2What is a 'Unit Test'?
  3. 3What does the 'Red' step in Test-Driven Development (TDD) represent?

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.