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, of type Product, 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
Give newProduct the type Product, the interface at the top of the code, so TypeScript knows it has an id, a number. You can add that number to "/products/" with +: TypeScript turns it into text for you, as JavaScript does. The last check compares two objects, so it needs assert.deepStrictEqual, with the body of the GET's answer and newProduct.
Free plan: 30 tutor messages. PRO is unlimited.
