Skip to the content

Writing tests

JavaScript · Unit 20: Testing and debugging

A test suite is a list of checks, each with its own name and each looking at one single thing.

That's the rule: one test, one idea. Here there are three ideas about isEven, and each one reads on its own.

function check(t, got, exp) {
  const r = got === exp ? "ok" : "BAD";
  console.log(r + " " + t);
}
function isEven(n) {
  return n % 2 === 0;
}
check("even", isEven(4), true);
check("odd", isEven(7), false);
check("zero", isEven(0), true);

Prints

ok even
ok odd
ok zero

The rest of the explanation is in the lesson, which is part of the full plan.

Exercises in this lesson

You do them in the app, which checks them on the spot and explains why.

  1. 1. Multiple choice

    clean strips spaces and lowercases. If this test prints BAD, what do you know?

  2. 2. Predict the output

    The same two ideas, now as two tests. What does it print?

  3. 3. Complete the code

    cut keeps the first three letters. Complete what you expect from a two-letter text.

  4. 4. Predict the output

    evens really does return [2, 4]. What do the two tests print?

  5. 5. Complete the code

    Complete it so same compares the contents of both arrays.

  6. 6. Put the lines in order

    Put together a check that works for arrays too: turn both sides into text and then decide the word.

  7. 7. Find the bug

    Both tests check the same length and both should print ok. The second one prints BAD. Which line has the bug?

  8. 8. Multiple choice

    isAdult(n) says whether n is 18 or more. You already tried 17 and 25. Which test is missing?

  9. 9. Predict the output

    card builds a record with three properties. What do the tests print?

  10. 10. Predict the output

    Both objects hold the same data. What does it print?

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →