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).
jest.fn() creates a mock function that tracks calls, arguments, and return values — mockReturnValue(val) for sync, mockResolvedValue(val) for a Promise, mockRejectedValue(err) for a rejected Promise, mockImplementation(fn) for custom logic. jest.mock('module-path') auto-mocks the entire module (all exports become jest.fn()); with a factory function jest.mock('./api', () => ({ fetchUser: jest.fn() })) for full control; hoisting: jest.mock() is automatically hoisted to the top of the file. jest.spyOn(obj, 'method') wraps an existing method — calls the real implementation by default; use .mockImplementation() to override; importantly: must restore after the test with jest.restoreAllMocks() or mockRestore().
- Module mock patterns: mock the global fetch API with jest.spyOn(global, 'fetch'); mock environment variables with process.env.MY_VAR = 'test'.
- Timer mocks: jest.useFakeTimers() replaces setTimeout/setInterval/Date; jest.runAllTimers() triggers all pending timers; jest.advanceTimersByTime(ms).
- Partial mocks: jest.requireActual('module') to mock part of a module while keeping the real implementation for the rest. clearMocks vs resetMocks vs restoreMocks: clear (reset calls/instances), reset (clear + remove implementations), restore (reset + restore spies to originals).