Typing Test Utilities
In this page:
Typed Fixture Factories
A typed fixture factory is a function that returns a fully-typed test object (like createUser(overrides?: Partial<User>): User), so every test gets a valid, type-checked object without repeating its full shape each time.
Example: Typed Fixture Factories
interface User {
id: number;
name: string;
}
function createUser(overrides?: Partial<User>): User {
return { id: 1, name: "Test User", ...overrides };
}
console.log(createUser({ name: "Ravi" }));
Typed Assertion Helpers
Typed assertion helpers wrap a custom check in a function with a asserts return type, letting TypeScript narrow the value's type in every line of the test that follows the assertion.
Example: Typed Assertion Helpers
function assertDefined<T>(value: T | undefined, msg: string): asserts value is T {
if (value === undefined) throw new Error(msg);
}
const maybe: number | undefined = 5;
assertDefined(maybe, "must be defined");
console.log(maybe + 1);
Typed Async Helpers
Typed async helpers — like a waitFor<T>(fn: () => T | Promise<T>): Promise<T> utility — preserve the resolved type through the wait, so the awaited result is usable without a manual type assertion.
Example: Typed Async Helpers
async function waitFor<T>(fn: () => T | Promise<T>): Promise<T> {
return fn();
}
waitFor(() => 42).then(console.log);
Typed Test Builders
A typed test builder uses a fluent, chainable API (.withName(Alice).withAge(30).build()) where each method narrows the return type, catching a missing required field at compile time.
Example: Typed Test Builders
class UserTestBuilder {
private name = "";
private age = 0;
withName(name: string): this { this.name = name; return this; }
withAge(age: number): this { this.age = age; return this; }
build() { return { name: this.name, age: this.age }; }
}
console.log(new UserTestBuilder().withName("Ravi").withAge(30).build());
Typed Mock Factories
A typed mock factory returns an object matching an interface but with every method replaced by a jest mock function, keeping the mock's shape in sync with the real interface it's standing in for.
Example: Typed Mock Factories
interface UserService {
getUser(id: number): string;
}
function createMockUserService(): UserService {
return { getUser: (id: number) => `mock-user-${id}` };
}
console.log(createMockUserService().getUser(1));
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: