Start learning free

LESSON 134 OF 173 · BACKEND: TESTS AND RUNNING IT

Test the Answer

Practice

Your first test checks only the status. A shop that answers 200 with the wrong list still passes it. To test the list itself, read the body: the client has already turned the JSON text into JavaScript values, and they are in response.body. For GET /products that is an array with one object per product.

Once the body is JavaScript data, you check it with tools you already know: length, array indexes and object properties. Here is a check on another route, product 2, the Notebook:

const response = await client.get("/products/2");
const product = response.body;
assert.strictEqual(product.price, 7);

The check runs your tests on the shop and on two broken copies: one leaves out the last product, the other lists the cheapest product first. Both still answer 200, so only a test of the body catches them. The output must be:

Your tests on the shop:
  products answer 200 ... ok
  products list ... ok
  2 tests: OK
Your tests on a copy that leaves out the last product:
  products answer 200 ... ok
  products list ... FAIL
    AssertionError: 3 != 4
  2 tests: 1 failed, so they caught this bug
Your tests on a copy that lists the cheapest product first:
  products answer 200 ... ok
  products list ... FAIL
    AssertionError: 'Pen' != 'Mug'
  2 tests: 1 failed, so they caught this bug

Your task: below the first test, write a test named "products list": GET /products, keep response.body in products, and check that there are 4 products and that the first one's name is "Mug".


Assignment
Follow the Coding Tutorial to write a second test that checks the list in the answer.


Hint
Arrays count from 0, so the first product is products[0], an object. A test stops at its first failed check, so each broken copy shows one message.


STEP 1 OF 6
    Ctrl + Enter to check