Tests must not depend on each other. If all your tests use the same app, they share one shop: a Plant added by one test is still there when the next test runs. Then a test can pass or fail just because of which test ran before it.
The fix is test.beforeEach. You give it a function, and that function is called before each test, every time, so it's the place to build fresh data. What it puts in a variable declared outside the functions, the test that runs next can use.
let cart;
test.beforeEach(() => {
cart = [];
});
test("add", () => {
cart.push("Mug");
assert.strictEqual(cart.length, 1);
});
test("empty", () => {
assert.strictEqual(cart.length, 0);
});
"add" runs first and puts a Mug in the cart, yet "empty" still finds an empty cart: the function made a new one before it. In the shop, createApp() does that job: each call builds a new app with its own four products. With a new shop in every test, your two tests get these answers in any order:
"add product": POST /products (a Plant) → {"id": 5, …}
"count products": GET /products → a list of 4 products
The check runs your tests, then again in the opposite order, then once more with every test on the same shop, to show what fresh data saves you from. It must print:
Your tests on the shop:
add product ... ok
count products ... ok
2 tests: OK
Your tests again, in the opposite order:
count products ... ok
add product ... ok
2 tests: OK
Your tests if every test got the same shop:
add product ... ok
count products ... FAIL
AssertionError: 5 != 4
2 tests: 1 failed
Your task: above the "add product" test, call test.beforeEach with a function that builds a new app with createApp(), keeps it in a constant app, and puts its test client in client, the variable declared at the top. Then, below "add product", write a test named "count products": GET /products with client and check that the list has 4 products.
Assignment
Follow the Coding Tutorial to give every test a fresh shop with test.beforeEach, then test that the shop still has 4 products.
Hint
The name is beforeEach, with a capital E, and you call it on test. Inside its function, put the client in client with no const or let in front: the variable already exists at the top, so the tests can reach it. .length counts the items of an array.
Free plan: 30 tutor messages. PRO is unlimited.
