Lesson 2 of 7
Typed Mocks & Spies
Jest mocks replace real implementations with tracked fakes. TypeScript requires that mock types match the original interface. `jest.fn()` is typed as `jest.Mock<ReturnType, ArgsType>`. Understanding how to mock typed dependencies cleanly prevents `any` from creeping into test files.
Typed Mocks - jest.fn, spyOn & Module Mocking
// ── Typed jest.fn() ──────────────────────────────────────────
// The generic signature: jest.fn<ReturnType, ArgsType[]>
const mockFindById = jest.fn<
Promise<Task | null>,
[id: number]
>();
// Configure return values:
mockFindById.mockResolvedValueOnce(task1); // resolves with task1 once
mockFindById.mockResolvedValue(null); // then always resolves null
mockFindById.mockRejectedValue(new Error()); // or rejects
// ── Typed mock repository ─────────────────────────────────────
// Pattern: cast jest.fn() to the interface method type
function createMockRepository(): jest.Mocked<ITaskRepository> {
return {
findById: jest.fn(),
findAll: jest.fn(),
save: jest.fn(),
delete: jest.fn(),
};
}
// jest.Mocked<T> makes every method in T a jest.Mock - fully typed
// Usage in tests:
describe("TaskService", () => {
let repo: jest.Mocked<ITaskRepository>;
let service: TaskService;
beforeEach(() => {
repo = createMockRepository();
service = new TaskService(repo, mockNotifier, mockLogger);
});
it("returns a task when found", async () => {
repo.findById.mockResolvedValue(task1);
const result = await service.findById(1);
expect(repo.findById).toHaveBeenCalledWith(1);
expect(repo.findById).toHaveBeenCalledTimes(1);
if (result.ok) {
expect(result.value.title).toBe(task1.title);
} else {
fail("Expected success result");
}
});
it("returns failure when task not found", async () => {
repo.findById.mockResolvedValue(null);
const result = await service.findById(999);
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.error).toBeInstanceOf(NotFoundError);
}
});
});
// ── jest.spyOn - mock a method on a real object ──────────────
it("calls save after creation", async () => {
const repo = new InMemoryTaskRepository();
const saveSpy = jest.spyOn(repo, "save");
const service = new TaskService(repo, mockNotifier, mockLogger);
await service.create({ title: "Test", priority: "low" });
expect(saveSpy).toHaveBeenCalledTimes(1);
expect(saveSpy).toHaveBeenCalledWith(expect.objectContaining({ title: "Test" }));
});
// ── Module mock - mock entire ES module ───────────────────────
jest.mock("@/lib/taskApi", () => ({
taskApi: {
getAll: jest.fn(),
getById: jest.fn(),
create: jest.fn(),
},
}));
import { taskApi } from "@/lib/taskApi";
const mockTaskApi = taskApi as jest.Mocked<typeof taskApi>;Common Mistakes
- Using `as any` in mock types - never cast a mock to `any` to silence type errors. If the mock's type doesn't match the interface, fix the mock. Type errors in tests reveal mismatches between mock and real interface.
- Not resetting mocks between tests - mocked function call counts and implementations carry over between tests without `jest.clearAllMocks()` in `beforeEach`. Use `jest.resetAllMocks()` to also clear mock return values.
- Mocking things you don't own - don't mock third-party libraries (like axios). Wrap them in your own adapter, then mock the adapter. This also makes it easier to swap the underlying library later.
Tip
Tip
Practice Typed Mocks Spies in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for Typed Mocks & Spies
Practice Task
Note
Practice Task - (1) Write a working example of Typed Mocks Spies from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Typed Mocks Spies is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready typescript code.
Key Takeaways
- Jest mocks replace real implementations with tracked fakes.
- Using `as any` in mock types - never cast a mock to `any` to silence type errors. If the mock's type doesn't match the interface, fix the mock. Type errors in tests reveal mismatches between mock and real interface.
- Not resetting mocks between tests - mocked function call counts and implementations carry over between tests without `jest.clearAllMocks()` in `beforeEach`. Use `jest.resetAllMocks()` to also clear mock return values.
- Mocking things you don't own - don't mock third-party libraries (like axios). Wrap them in your own adapter, then mock the adapter. This also makes it easier to swap the underlying library later.
Finished this lesson?