jest.fn() tạo mock function tracking calls, arguments, return values — mockReturnValue(val) cho sync, mockResolvedValue(val) cho Promise, mockRejectedValue(err) cho rejected Promise, mockImplementation(fn) cho custom logic. jest.mock('module-path') auto-mock toàn bộ module (tất cả exports thành jest.fn()); với factory function jest.mock('./api', () => ({ fetchUser: jest.fn() })) cho control toàn diện; hoisting: jest.mock() được hoisted lên đầu file tự động. jest.spyOn(obj, 'method') wrap existing method — vẫn gọi real implementation mặc định, dùng .mockImplementation() để override; quan trọng: phải restore sau test bằng jest.restoreAllMocks() hoặc mockRestore().
- Module mock patterns: mock fetch API toàn cục với jest.spyOn(global, 'fetch'); mock environment variables với process.env.MY_VAR = 'test'.
- Timer mocks: jest.useFakeTimers() replace setTimeout/setInterval/Date; jest.runAllTimers() trigger tất cả pending timers; jest.advanceTimersByTime(ms).
- Partial mocks: jest.requireActual('module') để mock một phần module và giữ lại real implementation cho phần còn lại. clearMocks vs resetMocks vs restoreMocks: clear (reset calls/instances), reset (clear + remove implementations), restore (reset + restore spies to originals).