|
| 1 | +# A Beginner's Guide to Testing Functions |
| 2 | + |
| 3 | +## 1. What Is a Function? |
| 4 | + |
| 5 | +``` |
| 6 | +Input ──▶ Function ──▶ Output |
| 7 | +``` |
| 8 | + |
| 9 | +A ***pure function*** |
| 10 | +- Takes **input** (via **arguments**) |
| 11 | +- Does some work |
| 12 | +- Yields **one output** (via a **return value**) |
| 13 | + |
| 14 | +Example: |
| 15 | + |
| 16 | +``` |
| 17 | +sum(2, 3) → 5 |
| 18 | +``` |
| 19 | + |
| 20 | +Important idea: the same input should produce the same output. |
| 21 | + |
| 22 | + |
| 23 | +## 2. Testing Means Predicting |
| 24 | + |
| 25 | +Testing means: |
| 26 | +> If I give this input, what output should I get? |
| 27 | +
|
| 28 | + |
| 29 | +## 3. Choosing Good Test Values |
| 30 | + |
| 31 | +### Step 1: Determining the space of possible inputs |
| 32 | +Ask: |
| 33 | +- What type of value is expected? |
| 34 | +- What values make sense? |
| 35 | + - If they are numbers: |
| 36 | + - Are they integers or floating-point numbers? |
| 37 | + - What is their range? |
| 38 | + - If they are strings: |
| 39 | + - What are their length and patterns? |
| 40 | +- What values would not make sense? |
| 41 | + |
| 42 | +### Step 2: Choosing Good Test Values |
| 43 | + |
| 44 | +#### Normal Cases |
| 45 | + |
| 46 | +These confirm that the function works in normal use. |
| 47 | + |
| 48 | +- What does a typical, ordinary input look like? |
| 49 | + |
| 50 | +#### Boundary Cases |
| 51 | + |
| 52 | +Test values exactly at, just inside, and just outside defined ranges. |
| 53 | +These values are where logic breaks most often. |
| 54 | + |
| 55 | +#### Consider All Outcomes |
| 56 | + |
| 57 | +Every outcome must be reached by at least one test. |
| 58 | + |
| 59 | +- How many different results can this function produce? |
| 60 | +- Have I tested a value that leads to each one? |
| 61 | + |
| 62 | +#### Crossing the Edges and Invalid Values |
| 63 | + |
| 64 | +This tests how the function behaves when assumptions are violated. |
| 65 | +- What happens when input is outside of the expected range? |
| 66 | +- What happens when input is not of the expected type? |
| 67 | +- What happens when input is not in the expected format? |
| 68 | + |
| 69 | +## 4. How to Test |
| 70 | + |
| 71 | +### 1. Using `console.assert()` |
| 72 | + |
| 73 | +```javascript |
| 74 | + // Report a failure only when the first argument is false |
| 75 | + console.assert( sum(4, 6) === 10, "Expected 4 + 6 to equal 10" ); |
| 76 | +``` |
| 77 | + |
| 78 | +It is simpler than using `if-else` and requires no setup. |
| 79 | + |
| 80 | +### 2. Jest Testing Framework |
| 81 | + |
| 82 | +```javascript |
| 83 | + test("Should correctly return the sum of two positive numbers", () => { |
| 84 | + expect( sum(4, 6) ).toEqual(10); |
| 85 | + ... // Can test multiple samples |
| 86 | + }); |
| 87 | + |
| 88 | +``` |
| 89 | + |
| 90 | +Jest supports many useful functions for testing but requires additional setup. |
0 commit comments