Start learning free

LESSON 136 OF 173 · BACKEND: TESTS AND RUNNING IT

Test a POST

Practice

Your tests so far only read the shop. A test can also add to it: client.post sends a POST request. The body goes in send, chained right after it: give it an object and the client sends it as JSON, which with fetch you did yourself with JSON.stringify.

test("add customer", async () => {
  const client = request(app);
  const response = await client.post("/customers").send({ name: "Ana" });
  assert.strictEqual(response.status, 201);
});

A 201 Created only says the app answered well. It doesn't prove that the new thing was saved. To know that, the test asks for it back with a GET, using the id from the answer, and checks that it gets the same thing.

In the shop, the Plant gets the next id, 5, and asking for product 5 must give back the very same product:

POST /products  {"name": "Plant", "price": 15, "category": "home"}
  →  201  {"id": 5, "name": "Plant", "price": 15, "category": "home"}
GET /products/5  →  the same product

The check runs your tests on the shop, then on two broken copies: one answers 201 but never saves the product, the other gives every new product the id 1. Your tests must pass on the shop and catch both copies:

Your tests on the shop:
  one product ... ok
  add product ... ok
  2 tests: OK
Your tests on a copy that answers 201 but never saves the product:
  one product ... ok
  add product ... FAIL
    AssertionError: { error: 'Product not found' } != { id: 5, name: 'Plant', price: 15, category: 'home' }
  2 tests: 1 failed, so they caught this bug
Your tests on a copy that gives every new product the id 1:
  one product ... ok
  add product ... FAIL
    AssertionError: { id: 1, name: 'Mug', price: 12, category: 'kitchen' } != { id: 1, name: 'Plant', price: 15, category: 'home' }
  2 tests: 1 failed, so they caught this bug

Your task: below the "one product" test, write a test named "add product". With one client, POST a Plant (price 15, category "home") to /products, check that the status is 201, keep the JSON body in newProduct, then GET /products/ followed by its id and check that this answer equals newProduct.


Assignment
Follow the Coding Tutorial to write a test that POSTs a product and then GETs it back.


Hint
The id in newProduct.id is a number, but you can add it to "/products/" with +: JavaScript turns it into text for you. The last check compares two objects, so it needs assert.deepStrictEqual, with the body of the GET's answer and newProduct.


STEP 1 OF 7
    Ctrl + Enter to check