Lesson 6 / الدرس 6

Assertions with teeth / توكيدات لها أنياب

An assertion is where your judgement about what is correct becomes executable. Write it too loosely and the test passes forever while the product decays; too tightly and it fails every week for reasons nobody cares about.

التوكيد هو حيث يصير حكمك على ما هو صحيح قابلًا للتنفيذ. اكتبه فضفاضًا ينجح الاختبار إلى الأبد بينما يتحلل المنتج؛ واكتبه ضيّقًا يرسب كل أسبوع لأسباب لا يبالي بها أحد.

Everything before the assertion is setup. The assertion is the test. It is the single line where "this is what correct means" stops being an opinion in your head and becomes something a machine will enforce at three in the morning — which is why a weak one is so expensive: it enforces almost nothing, convincingly.

Too loose, too tight, and right

AssertionProblem
status is not 500Passes on 404, 401, 302 — almost anything
the body contains "order"Passes on "order not found"
the whole body equals this exact JSONFails when an unrelated field is added
status is 201 and body.id is a number and body.total is 550Right: specific about what matters, silent about the rest

The first two are the common failure and they look like tests. The third is the over-correction, and it is why some suites need repairing after every release.

// Weak. Green forever, and it is checking that a server exists.
expect(res.status).not.toBe(500);
expect(body).toBeTruthy();

// Brittle. Red the day someone adds a field nobody asked you about.
expect(body).toEqual({ id: 44, total: 550, currency: 'EGP', createdBy: 'sara' });

// Right. Names what the rule promised, ignores what it did not.
expect(res.status).toBe(201);
expect(typeof body.id).toBe('number');
expect(body.total).toBe(550);            // 500 + 10%, the rule under test
expect(body.password).toBeUndefined();   // and nothing that must never appear
The comment on the third block is doing real work: 550 means nothing to a reader six months from now, and // 500 + 10% turns a magic number back into the rule it came from.

Prove the assertion can fail

A test you have only ever seen pass is a test you have not finished. Break it on purpose once: change the expected total to a wrong number and watch it go red, then change it back. That thirty seconds is the difference between a test and a decoration, and it is the single habit that most separates people who trust their suite from people who quietly do not.

Check yourself / اختبر نفسك

1. What is wrong with asserting only that the status is not 500?

2. Why is asserting the entire response body equal to one exact object usually a mistake?

3. Why break a passing test on purpose?