Matcher & Assertions — Testing

Apa itu Matcher? Matcher adalah method yang digunakan untuk memverifikasi apakah suatu nilai sesuai ekspektasi. Vitest (dan Jest) menyediakan banyak matcher baw

Apa itu Matcher?

Matcher adalah method yang digunakan untuk memverifikasi apakah suatu nilai sesuai ekspektasi. Vitest (dan Jest) menyediakan banyak matcher bawaan untuk berbagai tipe data.

Equality Matcher

toBe vs toEqual

// toBe — strict equality (===), cek referensi untuk object
expect(2 + 2).toBe(4);
expect("halo").toBe("halo");

// toEqual — deep equality, cocok untuk object dan array
expect({ nama: "Budi" }).toEqual({ nama: "Budi" }); // ✅
expect({ nama: "Budi" }).toBe({ nama: "Budi" });    // ❌ referensi beda

Aturan praktis: Gunakan toBe untuk primitif (string, number, boolean), gunakan toEqual untuk object dan array.

Truthiness Matcher

expect(true).toBeTruthy();
expect(false).toBeFalsy();
expect(null).toBeNull();
expect(undefined).toBeUndefined();
expect("ada").toBeDefined();

// Truthy: nilai yang dianggap true (selain 0, "", null, undefined, NaN)
expect(1).toBeTruthy();
expect("teks").toBeTruthy();
expect(0).toBeFalsy();
expect("").toBeFalsy();

Number Matcher

expect(10).toBeGreaterThan(5);
expect(10).toBeGreaterThanOrEqual(10);
expect(3).toBeLessThan(5);
expect(3).toBeLessThanOrEqual(3);

// Untuk floating point, gunakan toBeCloseTo
expect(0.1 + 0.2).toBeCloseTo(0.3); // ✅
expect(0.1 + 0.2).toBe(0.3);       // ❌ floating point error

String Matcher

expect("Halo Dunia").toMatch(/Halo/);
expect("Halo Dunia").toMatch("Dunia");
expect("Halo Dunia").toContain("Dunia");

Array & Object Matcher

const buah = ["apel", "mangga", "jeruk"];

expect(buah).toContain("mangga");
expect(buah).toHaveLength(3);

const user = { nama: "Budi", umur: 25, alamat: { kota: "Jakarta" } };

expect(user).toMatchObject({ nama: "Budi" }); // partial match
expect(user).toHaveProperty("alamat.kota");
expect(user).toHaveProperty("umur", 25);

Error Matcher

function bagi(a, b) {
  if (b === 0) throw new Error("Tidak bisa membagi dengan nol");
  return a / b;
}

expect(() => bagi(10, 0)).toThrow();
expect(() => bagi(10, 0)).toThrow("Tidak bisa membagi dengan nol");
expect(() => bagi(10, 0)).toThrow(/nol/);

Negasi dengan .not

expect(5).not.toBe(3);
expect([1, 2, 3]).not.toContain(4);
expect({ a: 1 }).not.toEqual({ a: 2 });

Tips Pemilihan Matcher

Yang akan kamu pelajari