Lesson 2.4
Why tests fail
7 min · 8 steps
Step 1 of 8 · Explanation
Tests don't read the screen. A test calls your function, takes the value it returns, and compares it with the expected value.
Say
solution(2, 3)computesconst sum = a + b, then callsconsole.log(sum). The screen shows5, but the function returns nothing. To the test, the result isundefined.Step 2 of 8 · Pick the approach
The test expects
6. Your function prints6to the console, and the test still fails. Why?- The function returns nothing, so the result is
undefined - The console prints
6as a string console.logis too slow for the test- The test needs
console.logto be called twice
- The function returns nothing, so the result is
Step 3 of 8 · Predict the result
Problem "Return the sum of the digits in the string
s." What does it return for"123"?function solution(s) { let total = 0 for (const ch of s) { total += ch } return total}"0123"6"6"123
Step 4 of 8 · Pick the approach
The test expects
3. Your function returns"3". Does it pass?- No. Tests compare the type too, and a number isn't a string
- Yes, because they look the same on screen
- Yes, because JavaScript converts it automatically with
==
Step 5 of 8 · Predict the result
What does it return for
[3, 1, 2]?function solution(nums) { const sorted = nums sorted.sort((a, b) => a - b) return [nums[0], sorted[0]]}[1, 1][3, 1][3, 3]
Step 6 of 8 · Find the bug
Problem "Return a new array with every number doubled. Don't change
nums." The test checksnumsafter the call, and it fails. Tap the line that causes it.function solution(nums) { const result = nums for (let i = 0; i < result.length; i++) { result[i] = result[i] * 2 } return result}Step 7 of 8 · Write the code
solution(s)Return the sum of all digits in the string
s, as a number.
Constraints:0 ≤ s.length ≤ 100,sonly contains0to9.function solution(s) { // "123" -> 6 }Step 8 of 8 · Recap
- Tests only see the returned value.
console.logdoesn't count. 3and"3"are different. A number plus a string becomes a string.const b = adoesn't copy an array. Copy with[...a]before changing it.
- Tests only see the returned value.