Lesson 11 / الدرس 11

The shape of a readable test / شكل الاختبار المقروء

Every test is three parts in the same order: get ready, do the thing, check the result. Writing them as three visible blocks makes a failure legible at a glance, six months after you wrote it and forgot it.

كل اختبار ثلاثة أجزاء بالترتيب نفسه: تجهّز، وافعل الشيء، وافحص النتيجة. وكتابتها ثلاث كتل ظاهرة تجعل الرسوب مقروءًا بنظرة واحدة، بعد ستة أشهر من كتابتك له ونسيانك إياه.

A test with twenty lines and no structure takes five minutes to understand when it goes red at nine in the morning. The same test written as three labelled blocks takes ten seconds. You are not writing this for now; you are writing it for the morning it fails — which is the only morning anyone will ever read it.

Three blocks, one action

  1. Arrange. Everything that must be true before the interesting thing happens: sign in, create the record, go to the page.
  2. Act. The one thing under test. If there are two, it is two tests — and when it fails you will know which.
  3. Assert. What should now be true. Named specifically enough that the failure message alone tells the story.
test('a discount appears once the order passes 500', async ({ page }) => {
  // Arrange
  await signIn(page, 'sara@example.com');
  await page.goto('/product/44');          // costs 300

  // Act
  await page.getByLabel('Quantity').fill('2');
  await page.getByRole('button', { name: 'Add to basket' }).click();

  // Assert
  await expect(page.getByTestId('discount')).toHaveText('-60.00');  // 10% of 600
});
The comment on the assertion is doing the same work it did in the assertions lesson: -60.00 is a magic number, and // 10% of 600 is the rule it came from. Anyone reading the failure now knows what was expected and why.

The name is part of the test

A failing run prints the test name and little else. test('checkout') tells nobody anything at nine in the morning; test('a discount appears once the order passes 500') is a sentence someone can act on without opening the file. Name the behaviour, not the screen.

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

1. Why should a test have only one action in its Act block?

2. Why not assert that sign-in worked inside the arrange block of a discount test?

3. What makes a good test name?