Learn
← Previous Next →

Hari 24: TypeScript Testing Patterns

55 min Last updated 09 Apr 2026

Type-Safe Testing

// Test runner sederhana dengan TypeScript
type TestResult = { name: string; passed: boolean; error?: string };

function describe(suiteName: string, fn: () => void): void {
    console.log(`\n📦 ${suiteName}`);
    fn();
}

function it(testName: string, fn: () => void): TestResult {
    try {
        fn();
        console.log(`  ✅ ${testName}`);
        return { name: testName, passed: true };
    } catch (e) {
        console.log(`  ❌ ${testName}: ${(e as Error).message}`);
        return { name: testName, passed: false, error: (e as Error).message };
    }
}

function expect(actual: T) {
    return {
        toBe: (expected: T) => {
            if (actual !== expected)
                throw new Error(`Expected ${JSON.stringify(expected)}, got ${JSON.stringify(actual)}`);
        },
        toEqual: (expected: T) => {
            if (JSON.stringify(actual) !== JSON.stringify(expected))
                throw new Error(`Expected ${JSON.stringify(expected)}, got ${JSON.stringify(actual)}`);
        },
        toBeTruthy: () => { if (!actual) throw new Error(`Expected truthy, got ${actual}`); },
        toThrow: (fn: () => void) => {
            try { fn(); throw new Error("Expected to throw but didn't"); }
            catch {}
        }
    };
}

💡 Notice: Testing membuat refactoring aman. toBeTruthy/toBeFalsy lebih fleksibel dari toBe(true/false) karena menerima semua truthy/falsy values.

Assignment

Gunakan framework test di atas untuk test class Stack<T>: push, pop, peek, isEmpty, size. Tulis minimal 5 test cases.

Expected output:

Semua test berhasil!
TS index.ts
Solution
Output