The highlight of this answer is jest.requireActual(), this is a very useful utility that says to jest that "Hey keep every original functionalities intact and import them".

Copyjest.mock('./utilities.js', () => ({
  ...jest.requireActual('./utilities.js'),
  speak: jest.fn(),
}));

Let's take another common scenario, you're using enzyme ShallowWrapper and it doesn't goes well with useContext() hook, so what're you gonna do? While i'm sure there are multiple ways, but this is the one I like:

Copyimport React from "react";

jest.mock("react", () => ({
  ...jest.requireActual("react"), // import and retain the original functionalities
  useContext: jest.fn().mockReturnValue({foo: 'bar'}) // overwrite useContext
}))

The perk of doing it this way is that you can still use import React, { useContext } from "react" in your original code without worrying about converting them into React.useContext() as you would if you're using jest.spyOn(React, 'useContext')

Answer from Popsicle on Stack Overflow
🌐
Chakshunyu
chakshunyu.com › blog › how-to-mock-only-one-function-from-a-module-in-jest
How To Mock Only One Function From A Module In Jest | A technical blog by Chak Shun Yu
What we’ve basically done is mock the entire module, create a snapshot of the actual imports of the module, use that snapshot as the mocked version, and then tweak any import as we like for our test environment by overriding it in the mocked module. In this case we only wanted to mock the functionToMock function, so we only had to override that with a jest mock function. Due to the “throw away everything and start from scratch” nature of this approach, it is best served as a last resort solution when trying to mock one particular function from a module in Jest.
Top answer
1 of 7
347

The highlight of this answer is jest.requireActual(), this is a very useful utility that says to jest that "Hey keep every original functionalities intact and import them".

Copyjest.mock('./utilities.js', () => ({
  ...jest.requireActual('./utilities.js'),
  speak: jest.fn(),
}));

Let's take another common scenario, you're using enzyme ShallowWrapper and it doesn't goes well with useContext() hook, so what're you gonna do? While i'm sure there are multiple ways, but this is the one I like:

Copyimport React from "react";

jest.mock("react", () => ({
  ...jest.requireActual("react"), // import and retain the original functionalities
  useContext: jest.fn().mockReturnValue({foo: 'bar'}) // overwrite useContext
}))

The perk of doing it this way is that you can still use import React, { useContext } from "react" in your original code without worrying about converting them into React.useContext() as you would if you're using jest.spyOn(React, 'useContext')

2 of 7
73

The most straightforward way is to use jest.spyOn and then .mockImplementation(). This will allow all other functions in the module to continue working how they're defined.

For packages:

Copyimport axios from 'axios';

jest.spyOn(axios, 'get');
axios.get.mockImplementation(() => { /* do thing */ });

For modules with named exports:

Copyimport * as utils from './utilities.js';

jest.spyOn(utils, 'speak');
utils.speak.mockImplementation(() => { /* do thing */ });

Docs here: https://jestjs.io/docs/en/jest-object#jestspyonobject-methodname

Discussions

How to mock only a non-default function in Jest
I think you need to set __esModule: true in your jest object in order for the default export to work properly. There's an example here: https://archive.jestjs.io/docs/en/23.x/jest-object More on reddit.com
🌐 r/reactjs
4
4
November 6, 2023
Testing Jest Problem: Cannot mock and unmock in the same file
It sounds like you're replacing too much of the unit you are testing. I would instead try and create the scenario where the function in the try block throws an error all on its own. If it can't simulate a state where it throws naturally then something else is wrong. More on reddit.com
🌐 r/node
9
2
January 15, 2022
Jest Mocking.. mocking an internal property of a factory function
Hi OP. As a general rule, whenever you find yourself in a situation where you are having to mock things in Jest, and especially when it isn't straightforward, you should consider refactoring your code to use Dependency Injection. It looks like the solution to your problem as-is is using `jest.requireActual` and mocking the return. I would not recommend this though, as it opens the door to side-effects appearing in your unit tests in the future without any change to this test on your part. More on reddit.com
🌐 r/typescript
6
1
June 19, 2024
How to have multiple mock return values for a method within a class within a module?
I see the issue. The following works: Replace the initial mock with jest.mock("@aws-sdk/client-sns", () => { return { SNSClient: jest.fn(), CreateTopicCommand: jest.fn(), SubscribeCommand: jest.fn(), }; }); And add the following at the beginning of my test SNSClient.mockImplementation(() => { return { send: jest .fn() .mockReturnValueOnce({ TopicArn: "fakeTopicArn" }) .mockReturnValueOnce({ SubscriptionArn: "fakeSubscriptionArn", }), }; }); More on reddit.com
🌐 r/reactjs
6
2
November 7, 2023
🌐
Jest
jestjs.io › mock functions
Mock Functions · Jest
May 7, 2026 - Now, in order to test this method without actually hitting the API (and thus creating slow and fragile tests), we can use the jest.mock(...) function to automatically mock the axios module.
🌐
Zirkelc
zirkelc.dev › posts › jest-mock-only-one-function-from-module
Mock Only One Function From Module With Jest
February 24, 2023 - Internally, these functions use the request function from the rest-api-request module to execute the REST API query. However, the API is rate-limited, and you want to avoid exceeding the rate limit during your tests. Therefore, you decide to mock the request function to return a fake user object, but leave the rest of the implementation unchanged to avoid side effects. import userService from './userService'; import { request } from 'rest-api-request'; jest.mock('rest-api-request', () => { const original = jest.requireActual('rest-api-request'); return { ...original, request: jest.fn(() => ({ id: 1, name: 'John Doe', email: 'john.doe@example.com', })), }; });
🌐
DEV Community
dev.to › zirkelc › how-to-mock-only-one-function-from-module-1kf6
How To Mock Only One Function From Module - DEV Community
April 12, 2023 - Internally, these functions use the request function from the rest-api-request module to execute the REST API query. However, the API is rate-limited, and you want to avoid exceeding the rate limit during your tests. Therefore, you decide to mock the request function to return a fake user object, but leave the rest of the implementation unchanged to avoid side effects. import userService from './userService'; import { request } from 'rest-api-request'; jest.mock('rest-api-request', () => { const original = jest.requireActual('rest-api-request'); return { ...original, request: jest.fn(() => ({ id: 1, name: 'John Doe', email: 'john.doe@example.com', })), }; });
🌐
Eloquentcode
eloquentcode.com › mock-only-a-single-function-from-a-module-with-jest
Mock Only a Single Function from a Module with Jest – eloquent code
const functions = require('./my-functions') describe('mock only one function from module', () => { it('should return only one mocked result', () => { jest.spyOn(functions, 'g') .mockImplementation(() => '_mock_') console.log(functions.f()) console.log(functions.g()) console.log(functions.h()) expect(functions.f()).toEqual('Return from f') expect(functions.g()).toEqual('_mock_') expect(functions.h()).toEqual('Return from h') }) })
🌐
Ben Ilegbodu
benmvp.com › blog › mock-all-functions-module-except-one-jest
Mock all functions in a JavaScript module except one using Jest | Ben Ilegbodu
A shorthand way with jest.mock() to auto-mock all functions in a JavaScript module yet use the real implementation of one function
🌐
JavaScript in Plain English
javascript.plainenglish.io › how-to-mock-a-single-function-from-a-module-with-jest-8f9994bf9410
How to Mock a Single Function from a Module with Jest | by Dunja Vesinger | JavaScript in Plain English
August 16, 2021 - ... First, you create a mock of a module using the jest.mock function. The mock function takes a string that represents a path to the local module or a name of the library you’d like to mock, just like an import statement does.
Find elsewhere
🌐
Medium
medium.com › welldone-software › jest-how-to-mock-a-function-call-inside-a-module-21c05c57a39f
Jest — How To Mock a Function Call Inside a Module | by Vitali Zaidman | Welldone Software | Medium
May 3, 2021 - test('a', () => { const f = require('./f'); jest.spyOn(f, 'b').mockReturnValue('c'); expect(f.a()).toBe('c'); // FAILED! // expected 'c' got 'b' }) Nope… It won’t work. That is because the exported b is mocked indeed, but it’s not the same b as the one that is called by a inside the module. ... // b.jsexport function b(){ return 'b'; }// f.jsimport {b} from './b';export function a(){ return b(); }
🌐
Medium
medium.com › @qjli › how-to-mock-specific-module-function-in-jest-715e39a391f4
How to mock specific module function in jest? | by QJ Li | Medium
September 21, 2018 - import { getFullName, greet } from './helper';describe('greet', () => { it('should return greet message with full name', () => { getFullName = jest.fn().mockReturnValue('mock full name'); const result = greet('QJ', 'Li'); expect(result).toBe('Hey, mock full name'); }); }); However, the result is not what you expect like above. The reason being, getFullName function in the helper.js is a local scope function and override it directly via jest.fn() won’t work here.
🌐
Bitovi
bitovi.com › blog › mocking-modules-in-jest-tests
Mocking Modules in Jest Tests
August 6, 2024 - You start by using the signature of jest.mock that accepts two parameters. The first parameter is the module-name to mock, the second parameter is a function that returns a module object.
🌐
pawelgrzybek
pawelgrzybek.com › mocking-functions-and-modules-with-jest
Mocking functions and modules with Jest | pawelgrzybek.com
April 12, 2020 - It works, but what if a module exports tens or hundreds of methods? Manually reassigning all of them would be cumbersome. Jest comes with a fantastic feature called automock that you can enable globally or inside individual test files using jest.mock() method.
🌐
Jest
jestjs.io › manual mocks
Manual Mocks · Jest
May 7, 2026 - If you do not want to use the automatic mock at all, you can export your own functions from the mock file. One downside to fully manual mocks is that they're manual – meaning you have to manually update them any time the module they are mocking changes. Because of this, it's best to use or extend the automatic mock when it works for your needs. To ensure that a manual mock and its real implementation stay in sync, it might be useful to require the real module using jest.requireActual(moduleName) in your manual mock and amending it with mock functions before exporting it.
🌐
Jest
jestjs.io › bypassing module mocks
Bypassing module mocks · Jest
May 7, 2026 - To get around problems like this, Jest provides the jest.requireActual helper. To make the above test work, make the following change to the imports in the test file: ... This allows your test file to import the actual Response object from node-fetch, rather than a mocked version.
🌐
DEV Community
dev.to › tylerlwsmith › override-functions-in-individual-tests-using-jest-dp5
Mock functions in individual tests using Jest - DEV Community
August 5, 2024 - The __esModule property is required whenever using a factory parameter in jest.mock to mock an ES module (docs). If you wanted, you could also replace an individual function in the factory parameter.
🌐
Reddit
reddit.com › r/reactjs › how to mock only a non-default function in jest
r/reactjs on Reddit: How to mock only a non-default function in Jest
November 6, 2023 -

I am trying to mock a non default function in jest which is part of a larger module and I don't want to mock any of the rest of it. I tried something along the lines of the solution found here (https://stackoverflow.com/questions/59312671/mock-only-one-function-from-module-but-leave-rest-with-original-functionality). The problem is that importing the default function gives you the whole module instead of the default function.

For example:

// myModule.js
export const foo = () => {
    console.log("in foo");
};

const bar = () => {
    console.log("in bar");
};

export default bar;
// useMyModule.test.js
import bar, { foo } from "./myModule";
import "./useMyModule";

jest.mock("./myModule", () => ({
    ...jest.requireActual("./myModule"),
    foo: jest.fn(() => {
        console.log("in test foo");
    }),
}));

test("see if this works", () => {
    console.log(bar);
    foo();
});
// useMyModule.js
import bar from "./myModule";

console.log(bar);
//bar(); // <== commented out because bar is not the function I expect it to be

This is what the output looks like:

 PASS  src/useMyModule.test.js
  ● Console

    console.log
      {
        default: [Function: bar],
        foo: [Function: mockConstructor] {
          _isMockFunction: true,
          getMockImplementation: [Function (anonymous)],
          mock: [Getter/Setter],
          mockClear: [Function (anonymous)],
          mockReset: [Function (anonymous)],
          mockRestore: [Function (anonymous)],
          mockReturnValueOnce: [Function (anonymous)],
          mockResolvedValueOnce: [Function (anonymous)],
          mockRejectedValueOnce: [Function (anonymous)],
          mockReturnValue: [Function (anonymous)],
          mockResolvedValue: [Function (anonymous)],
          mockRejectedValue: [Function (anonymous)],
          mockImplementationOnce: [Function (anonymous)],
          mockImplementation: [Function (anonymous)],
          mockReturnThis: [Function (anonymous)],
          mockName: [Function (anonymous)],
          getMockName: [Function (anonymous)]
        }
      }

      at Object.<anonymous> (src/useMyModule.js:3:9)

    console.log
      {
        default: [Function: bar],
        foo: [Function: mockConstructor] {
          _isMockFunction: true,
          getMockImplementation: [Function (anonymous)],
          mock: [Getter/Setter],
          mockClear: [Function (anonymous)],
          mockReset: [Function (anonymous)],
          mockRestore: [Function (anonymous)],
          mockReturnValueOnce: [Function (anonymous)],
          mockResolvedValueOnce: [Function (anonymous)],
          mockRejectedValueOnce: [Function (anonymous)],
          mockReturnValue: [Function (anonymous)],
          mockResolvedValue: [Function (anonymous)],
          mockRejectedValue: [Function (anonymous)],
          mockImplementationOnce: [Function (anonymous)],
          mockImplementation: [Function (anonymous)],
          mockReturnThis: [Function (anonymous)],
          mockName: [Function (anonymous)],
          getMockName: [Function (anonymous)]
        }
      }

      at Object.<anonymous> (src/useMyModule.test.js:12:13)

However, if you uncomment the bar() invocation above, you get this:

 FAIL  src/useMyModule.test.js
  ● Test suite failed to run

    TypeError: (0 , _myModule.default) is not a function

      2 |
      3 | console.log(bar);
    > 4 | bar();
        |    ^
      5 |

      at Object.<anonymous> (src/useMyModule.js:4:4)
      at Object.<anonymous> (src/useMyModule.test.js:2:1)

So, how should I mock the foo function, but leave the default bar function intact?

🌐
Mercedes Bernard
mercedesbernard.com › blog › jest-mocking-strategies
Jest Mocking Strategies | Mercedes Bernard
July 12, 2020 - Because the module is a function, we provide a factory that returns the mock function we want to be invoked instead of the module. In this example, we provided a mock implementation so we could set the return value. import example from ...
🌐
Cursor AI
emgoto.com › mocking-with-jest
A guide to mocking functions and modules with Jest
December 21, 2025 - When writing Jest unit tests, I always struggle to remember the syntax for mocking ES6 modules. So this post is intended as a part-guide, part-cheatsheet to refresh your memory. It covers: How to mock imported functions from a module using jest.mock() and jest.fn()
🌐
Luetkemj
luetkemj.github.io › 170421 › mocking-modules-in-jest
Mocking specific module functions with jest · luetkemj
// myModule.js import { random } from 'lodash'; export function testRandomMock() { return random(1, 10); } // myModule.test.js import * as myModule from './myModule.js'; // tell jest not to mock lodash jest.unmock('lodash'); // require the actual module so that we can mock exports on the module const lodash = require.requireActual('lodash'); test('random should be 1', () => { // mock lodash random to return the value 1 in first test lodash.random = jest.fn(() => 1); expect(myModule.testRandomMock(1)).toBe(1); }); test('random should be 2', () => { // mock lodash random to return the value 2 in second test lodash.random = jest.fn(() => 2); expect(myModule.testRandomMock(2)).toBe(2); });
🌐
Patrick Desjardins
patrickdesjardins.com › blog › typescript-and-jest-to-mock-a-module-function
Patrick Desjardins Blog - TypeScript and Jest to Mock a Module Function
March 8, 2024 - Not only it will be faster to avoid making HTTP calls, it will remove Jest to import the problematic import and the test is tailor toward the real tested function and not the functions that this one uses. Finally, mocking help consistency as we control the exact output of the dependency. The first step is to mock the direct dependency, the one that perform the HTTP request. jest.mock('../../service/entities', () => ({ getEntities: jest.fn().mockReturnValue([]), })); This command can be at the top of your test.ts file. For every invocation to the getEntities function in the service/entities file the function will return an empty array.