jest.mock() is invoked in the test case functional scope. Module imports are hoisted (internally moved to the beginning of the current scope). The original today function is imported before jest.mock() mocks the utils/date module.

You can move the jest.mock() from test case functional scope to module scope. Jest will automatically hoist jest.mock calls to the top of the module (before any imports). So that when you import the today function, it is already being mocked.

See Using with ES module imports:

If you're using ES module imports then you'll normally be inclined to put your import statements at the top of the test file. But often you need to instruct Jest to use a mock before modules use it. For this reason, Jest will automatically hoist jest.mock calls to the top of the module (before any imports).

import { today } from 'utils/date';

jest.mock('utils/date', () => ({
  today: jest.fn(() => '01-01-2020'),
}));

it('should work properly', () => {
  expect(jest.isMockFunction(today)).toBeTruthy();
  expect(today()).toBe('01-01-2020');
});
Answer from Lin Du on Stack Overflow
🌐
Jest
jestjs.io › mock functions
Mock Functions · Jest
1 week ago - Mock functions allow you to test the links between code by erasing the actual implementation of a function, capturing calls to the function (and the parameters passed in those calls), capturing instances of constructor functions when instantiated ...
Discussions

Testing Imported Function with Parameter using Jest Mock Function / Jest spyOn
I'm trying to write a unit test for a Node.js project's logic using Jest. However, most documentations only provide a case for importing a module or class, however, in my case, my module only conta... More on stackoverflow.com
🌐 stackoverflow.com
February 18, 2020
How can I mock an ES6 module import using Jest?
This is why it doesn't matter if yoour jest.mock is before or after your import. By placing it in a function body, it will not function correctly. 2020-12-21T13:07:34.75Z+00:00 ... The __esModule: true made it work where I needed to mock default exports. Otherwise it worked well without that. More on stackoverflow.com
🌐 stackoverflow.com
Anyone have an article/video around that's a deep dive on Jest imports and mocking?
I don't know if this clears things up but basically Jest transforms any code passed in (Technically Jest scripts are not JavaScript! They don't follow ES semantics! anyway) If Jest sees a "mock" call that gets hoisted up to the top of the program. The whole AST subnode gets yanked to the top. If there are any variables starting "mock..." these also get yanked to the top. This is why your mock functions can only refer to closure variables named using that pattern. This mock call ~messes about with~ carefully instruments the Node require function and its cache. Any functions you specify for mocks are attached as callbacks Now your subsequent import / require statements go through this instrumentation Node resolves imports a bit like a depth first search. If I'm Node and I see an import, I stop what I'm doing and try to eval the imported module or fetch the import result from my cache Knowing it starts with a DFS helps you reason about the order Jest mocks are called More on reddit.com
🌐 r/ExperiencedDevs
32
26
December 30, 2024
I hate mocking Typescript classes with Jest
Jest is a pain to make it work with TypeScript anyway. Try using something like Vitest with TypeScript support out of the box More on reddit.com
🌐 r/typescript
49
64
May 30, 2023
🌐
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.
🌐
DEV Community
dev.to › dstrekelj › how-to-mock-imported-functions-with-jest-3pfl
How to mock imported functions with Jest - DEV Community
August 3, 2021 - To support ES module imports - where import statements have to come first in a file - Jest automatically hoists jest.mock() calls to the top of the module. Read more about this technique here. To check if a function was called correctly with Jest we use the expect() function with specific matcher methods to create an assertion.
🌐
Jest
jestjs.io › es6 class mocks
ES6 Class Mocks · Jest
... Usage is similar to the module factory function, except that you can omit the second argument from jest.mock(), and you must import the mocked method into your test file, since it is no longer defined there.
🌐
Cursor AI
emgoto.com › mocking-with-jest
A guide to mocking functions and modules with Jest
December 21, 2025 - For the purposes of this page, let’s assume that we have a ES6 module that has two named exports (getTime and isMorning), and one default import: ... // Our named exports export const getTime = () => '14:30'; export const isMorning = () => false; // Our default export const getDayOfWeek = () => 'Monday'; export default getDayOfWeek; We can mock the functions that a module returns using Jest’s .mock().
🌐
GitHub
gist.github.com › gadflying › 5f2bf3c53370a0ceda5108816aedd298
[How to mock imported named function in Jest when module is unmocked] #jest #reactTestLib · GitHub
However, you'll also need to mock the return value of fetch with a Response (wrapped in a Promise), as our function uses it to grab the created user's ID. So you might initially try writing a test like this: ... import fetch, {Response} from 'node-fetch'; import {createUser} from './createUser'; test('createUser calls fetch with the right args and returns the user id', async () => { fetch.mockReturnValue(Promise.resolve(new Response('4'))); const userId = await createUser(); expect(fetch).toHaveBeenCalledTimes(1); expect(fetch).toHaveBeenCalledWith('http://website.com/users', { method: 'POST', }); expect(userId).toBe('4'); });
🌐
Chakshunyu
chakshunyu.com › blog › how-to-mock-the-return-value-of-an-imported-function-in-jest
How To Mock The Return Value Of An Imported Function In Jest | A technical blog by Chak Shun Yu
February 8, 2022 - To mock the return value of an imported function in Jest, you have to either call mockReturnValue or mockImplementation on a Jest mock function and then specify the return value. Which function mock function you should use depends on your situation.
Find elsewhere
🌐
DEV Community
dev.to › magpys › mocking-with-jest-and-typescript-a-cheatsheet-17ol
Mocking with Jest and typescript - a cheatsheet - DEV Community
January 6, 2025 - import { ComplicatedThing } from ... = jest.fn(); // typescript shenanigans - asserting that it IS a given type will // allow us to pass that into functions as a parameter of that type....
🌐
TypeOfNaN
typeofnan.dev › partially-mocking-imports-in-jest
Partially mocking imports in Jest | TypeOfNaN
June 30, 2021 - This is because we’re mocking the entire someModule module. Since we didn’t mock the returnSomething function exported from it, it’s not defined! To fix this, we can use jest.requireActual to require the actual module and keep around the function we want:
🌐
Tigeroakes
tigeroakes.com › tiger oakes › blog › when is it safe to use import statements in jest tests?
When is it safe to use import statements in Jest tests? | Tiger Oakes
December 27, 2022 - Here’s the checks I found from digging through the source code of Jest’s babel plugin. The first argument to jest.mock() should be a literal value. The second argument, if provided, should be an inline function.
🌐
Meticulous
meticulous.ai › blog › mocking-a-javascript-class-with-jest-two-ways-to-make-it-easier
Mocking a JavaScript Class with Jest, Two Ways to Make it Easier
It calls the API to fetch the latest exchange rates of the from currency and plucks out the rate of the to currency else returns 0. In case of any error, the catch block logs the error and returns back 0. Using the default parameters if the ...
🌐
Jest
jestjs.io › manual mocks
Manual Mocks · Jest
1 week ago - 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. The code for this example is available at examples/manual-mocks. If you're using ES module imports then you'll normally be inclined to put your import statements at the top of the test file.
🌐
Stack Overflow
stackoverflow.com › questions › 60273598 › testing-imported-function-with-parameter-using-jest-mock-function-jest-spyon
Testing Imported Function with Parameter using Jest Mock Function / Jest spyOn
February 18, 2020 - Cannot spy the getDefaultLocationCode property because it is not a function; undefined given instead · 31 | const spy = jest.spyOn(getDefaultLocationCode, 'getDefaultLocationCode'); ... error TS2349: This expression is not callable. Type 'typeof import("/app/src/controllers/logic/getDefAPCode")' has no call signatures. ... expect(received).toHaveBeenCalled() Matcher error: received value must be a mock or spy function Received has type: string Received has value: "NRT"
🌐
pawelgrzybek
pawelgrzybek.com › mocking-functions-and-modules-with-jest
Mocking functions and modules with Jest | pawelgrzybek.com
April 12, 2020 - thanks for the article. wanted to mock module with parameters , say i have add module and it return 3 when i pass value 1 and 2 and 4 when i pass 2 and 2. how this can be mocked ? Reply to Vikash Sharma ... I wouldn't advice to mock pure functions like `sum`. Just hit an actual implementation to test it. If you use `sum` just as an example, you need to look into something called `jest-when`. import { when } from 'jest-when'; const fn = jest.fn() when(fn) .calledWith(1, 2).mockReturnValue(3) .calledWith(2, 2).mockReturnValue(4); expect(fn(1)).toEqual('yay!') expect(fn(2)).toEqual('nay!') Reply to Pawel Grzybek
🌐
Medium
medium.com › @debihiga › typescript-jest-mock-imported-methods-classes-and-constants-f4ff51bf866f
Typescript + Jest: mock imported methods, classes and constants | by Debi Higa | Medium
September 20, 2023 - import { A_VALUE } from "../module"; jest.mock("../module", () => ({ ...jest.requireActual("../module"), __esModule: true, // Use it when dealing with esModules A_VALUE: 20 })); Or mock it per test: import * as aModule from "../module"; ...
🌐
The Reinvigorated Programmer
reprog.wordpress.com › 2021 › 10 › 21 › testing-with-jest-how-to-mock-an-import-used-by-the-module-youre-testing
Testing with Jest: how to mock an import used by the module you’re testing | The Reinvigorated Programmer
October 21, 2021 - export default function nameToGreet() { return 'Mike' }; Clearly calling greet() returns “Hello, Mike” — I have verified this. But from within my test-script I can mock the second module to change the greeting as follows (in src/experiment/MyModule.test.js): import greet from './MyModule'; import nameToGreet from './subdir/SubModule'; jest.mock('./subdir/SubModule'); nameToGreet.mockImplementation(() => 'Fiona'); test('Greets Fiona instead of Mike', () => { expect(greet()).toBe('Hello, Fiona'); });
🌐
Medium
medium.com › @stanleyclark › the-right-way-to-mock-function-imports-in-jest-using-typescript-7d1ff59d8b1d
The right way to mock function imports in Jest using TypeScript | by Stanley Clark | Medium
September 9, 2024 - That means that we have to mock the return of the function up-front, before we write a import { badFunc } from ‘./bad-func’; statement. So, this could look something like: import { badFunc } from './bad-func'; import { myFunc } from './my-func'; jest.mock('./my-func', () => ({ myFunc: jest.fn().mockReturnValueOnce(2), })); it('should mock the function', () => { const result = badFunc(2); expect(result).toBe(4); expect(myFunc).toHaveBeenCalledTimes(1); });
Top answer
1 of 11
304

Edit: Several years have passed and this isn't really the right way to do this any more (and probably never was, my bad).

Mutating an imported module is nasty and can lead to side effects like tests that pass or fail depending on execution order.

I'm leaving this answer in its original form for historical purposes, but you should really use jest.spyOn or jest.mock. Refer to the jest docs or the other answers on this page for details.

Original answer follows:


I've been able to solve this by using a hack involving import *. It even works for both named and default exports!

For a named export:

// dependency.js
export const doSomething = (y) => console.log(y)
// myModule.js
import { doSomething } from './dependency';

export default (x) => {
  doSomething(x * 2);
}
// myModule-test.js
import myModule from '../myModule';
import * as dependency from '../dependency';

describe('myModule', () => {
  it('calls the dependency with double the input', () => {
    dependency.doSomething = jest.fn(); // Mutate the named export

    myModule(2);

    expect(dependency.doSomething).toBeCalledWith(4);
  });
});

Or for a default export:

// dependency.js
export default (y) => console.log(y)
// myModule.js
import dependency from './dependency'; // Note lack of curlies

export default (x) => {
  dependency(x * 2);
}
// myModule-test.js
import myModule from '../myModule';
import * as dependency from '../dependency';

describe('myModule', () => {
  it('calls the dependency with double the input', () => {
    dependency.default = jest.fn(); // Mutate the default export

    myModule(2);

    expect(dependency.default).toBeCalledWith(4); // Assert against the default
  });
});

2 of 11
294

You have to mock the module and set the spy by yourself:

import myModule from '../myModule';
import dependency from '../dependency';
jest.mock('../dependency', () => ({
  doSomething: jest.fn()
}))

describe('myModule', () => {
  it('calls the dependency with double the input', () => {
    myModule(2);
    expect(dependency.doSomething).toBeCalledWith(4);
  });
});
🌐
Robert Marshall
robertmarshall.dev › home › blog › how to mock an es6 module import using jest
How to Mock an ES6 Module Import using Jest - Robert Marshall
November 21, 2022 - import functionToTest from ... React Testing Library. What we are doing is importing the particular functions that need to be mocked, and then mocking the whole file with Jest....