Koskamo

Mock functions and module mocking

Document v1 · published by Koskamo editorial · updated 2026-10-04

Original source

Mock functions test the links between code by erasing a function's real implementation while capturing calls and their parameters, capturing constructor instances created with new, and allowing test-time configuration of return values. Create one directly with jest.fn for use in test code, or write a manual mock to override a module dependency. Every mock exposes a .mock property recording calls and results, the this value per call (mock.contexts), constructor instantiations (mock.instances), and the last call's arguments (mock.lastCall). Queue return values with mockReturnValueOnce and mockReturnValue, or replace behavior with mockImplementation and one-shot mockImplementationOnce; when the one-shot queue empties, the default implementation from jest.fn runs. For modules, jest.mock('axios') automatically mocks the dependency so axios.get.mockResolvedValue(resp) injects a fake response without hitting the API, and a jest.mock factory can spread jest.requireActual to mock only part of a module. Keep logic out of mocked functions that are not directly under test. Scope: Jest. Reviewed October 4, 2026.

Source and provenance

Original source
jestjs.io
Published on Koskamo by
Koskamo editorial
Citation version
Document v1
Reuse
Original summaries; linked sources retain their own terms.

The original source supplies the underlying information. Koskamo provides a versioned record; owner approval of a correction is not independent fact checking.