typescript / intermediate
Snippet
Creating Type-Safe Test Doubles with Spy Interfaces
Creating test doubles by implementing domain interfaces allows unit testing without reliance on external mocking frameworks. The mock class records call parameters for assertions while satisfying standard interface contracts.
snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
interface DataStore {save(key: string, value: string): void;find(key: string): string | null;}class MockDataStore implements DataStore {public saveCalls: Array<{ key: string; value: string }> = [];private storage = new Map<string, string>();save(key: string, value: string): void {this.saveCalls.push({ key, value });this.storage.set(key, value);}find(key: string): string | null {return this.storage.get(key) ?? null;}}const mockStore = new MockDataStore();mockStore.save("user_101", "Active");console.assert(mockStore.saveCalls.length === 1, "Should record one save call");
Breakdown
1
interface DataStore {
Defines the contract required by production logic for storage operations.
2
class MockDataStore implements DataStore {
Implements the storage contract inside a custom test double class.
3
public saveCalls: Array<{ key: string; value: string }> = [];
Stores invocation history to enable assertion inspection during unit tests.
4
console.assert(mockStore.saveCalls.length === 1, "Should record one save call");
Verifies that the mock recorded the interaction correctly using standard assertion tools.