BDD & Penamaan Test — Testing

Test adalah Dokumentasi Hidup Test bukan cuma untuk mencegah bug — test adalah dokumentasi yang dieksekusi. Developer baru membaca nama test untuk mengerti sist

Test adalah Dokumentasi Hidup

Test bukan cuma untuk mencegah bug — test adalah dokumentasi yang dieksekusi. Developer baru membaca nama test untuk mengerti sistem. Nama yang buruk bikin test suite jadi beban, bukan aset.

Anti-Pattern: Nama Test yang Buruk

// ❌ Tidak jelas
test("test1", () => { ... });
test("testAdd", () => { ... });
test("cart", () => { ... });
test("should work", () => { ... });

// Saat gagal, kamu hanya tahu "test1 gagal". Gagalnya apa? Tidak tahu.

Pola: Given-When-Then (Gherkin)

BDD (Behavior-Driven Development) pakai struktur yang dipinjam dari bahasa natural. Format Gherkin:

Feature: Keranjang belanja
  Scenario: Menambah item ke keranjang kosong
    Given keranjang dalam keadaan kosong
    When user menambahkan produk "Buku"
    Then keranjang berisi 1 item
    And total harga sama dengan harga buku

Given-When-Then di Kode Test

Struktur Gherkin juga bisa dibawa ke test biasa — dengan nama yang deskriptif dan komentar:

describe("Keranjang Belanja", () => {
  it("should add item when addToCart is called with valid product", () => {
    // Given
    const cart = new Cart();
    const book = { id: 1, name: "Buku", price: 50000 };

    // When
    cart.addToCart(book);

    // Then
    expect(cart.items).toHaveLength(1);
    expect(cart.total).toBe(50000);
  });
});

AAA: Arrange-Act-Assert

Variasi yang sama populernya, lebih singkat:

Gherkin/GWT lebih cocok untuk test yang dibaca stakeholder (product, QA). AAA lebih ringkas untuk unit test developer.

Pola Penamaan yang Baik

Tiga pola populer, pilih satu lalu konsisten:

1. "should [expected] when [condition]"

it("should return 0 when dividing by zero");
it("should throw error when email is invalid");
it("should mark todo as done when toggle is clicked");

2. "when [condition], [expected]"

test("when user is logged out, redirect to login page");
test("when cart is empty, checkout button is disabled");

3. Imperative / Natural sentence

test("adds item to empty cart");
test("rejects negative quantity");
test("calculates total with tax included");

Pest & PHPUnit: it() dan describe()

Pest mendukung sintaks BDD ala Jest langsung dalam PHP:

describe("Cart", function () {
    it("should add item when product is valid", function () {
        // Given
        $cart = new Cart();
        // When
        $cart->add(new Product("Buku", 50000));
        // Then
        expect($cart->items)->toHaveCount(1);
    });

    it("should reject product with negative price", function () {
        $cart = new Cart();
        expect(fn() => $cart->add(new Product("X", -100)))
            ->toThrow(InvalidArgumentException::class);
    });
});

Checklist Nama Test yang Baik

Yang akan kamu pelajari