You can mock the module like this:

import calculate from '../../calculate'
jest.mock('../xyz', ()=> () => Promise.resolve('mocked value'))

it('does something', async()=>{
  const op = await calculate()
  expect(op).toBe('mocked value')
})

if you need different return values from your mock you need to mock the module so it returns a spy. Then you have to import the module and you can set the return value during your tests:

import calculate from '../../calculate'
import myModule from '../xyz'
jest.mock('../xyz', ()=> jest.fn())

it('does something', async() => {
  myModule.mockImplementation(() => () =>  Promise.resolve('mocked value'))

  const op = calculate()
  expect(op).toBe('mocked value')
})

it('does something else', async() => {
  myModule.mockImplementation(() => () =>  Promise.resolve('another value'))
  const op = await calculate()
  expect(op).toBe('another value')
})


it('does fail', async() => {
  myModule.mockImplementation(() => () =>  Promise.reject('some Error')
  try{
    const op = await calculate()
  }catch (e){
    expect(e).toBe('some Error')
  }
})

Answer from Andreas Köberle on Stack Overflow
🌐
Chakshunyu
chakshunyu.com › blog › how-to-spy-on-a-named-import-in-jest
How To Spy On An Exported Function In Jest | A technical blog by Chak Shun Yu
September 3, 2021 - import * as moduleApi from '@module/api'; // Somewhere in your test case or test suite jest.spyOn(moduleApi, 'functionToMock').mockReturnValue({ someObjectProperty: 42 });
Top answer
1 of 2
11

You can mock the module like this:

import calculate from '../../calculate'
jest.mock('../xyz', ()=> () => Promise.resolve('mocked value'))

it('does something', async()=>{
  const op = await calculate()
  expect(op).toBe('mocked value')
})

if you need different return values from your mock you need to mock the module so it returns a spy. Then you have to import the module and you can set the return value during your tests:

import calculate from '../../calculate'
import myModule from '../xyz'
jest.mock('../xyz', ()=> jest.fn())

it('does something', async() => {
  myModule.mockImplementation(() => () =>  Promise.resolve('mocked value'))

  const op = calculate()
  expect(op).toBe('mocked value')
})

it('does something else', async() => {
  myModule.mockImplementation(() => () =>  Promise.resolve('another value'))
  const op = await calculate()
  expect(op).toBe('another value')
})


it('does fail', async() => {
  myModule.mockImplementation(() => () =>  Promise.reject('some Error')
  try{
    const op = await calculate()
  }catch (e){
    expect(e).toBe('some Error')
  }
})

2 of 2
0

There's no need to mock, which is something of a broad sword, since it works at the module level. Jest's spyOn is a more focussed way of doing this, since it is at the method level.

The confusion here is solely because of the internal workings of 'xyz'. You have assumed that the module called 'xyz' has a function within it also called 'xyz'. Hence Jest fails to find it.

If we assume that 'xyz' is actually the default export of the 'xyz' module, we can test using this:

const mock = jest.spyOn(myModule, 'default')

All of the rest of your test code is perfect:

mock.mockReturnValue('mocked value')
const op = calculate()
expect(op).toBe('mocked value')
Discussions

Jest: How to spy on an imported function
How would you do this if you were mocking the functionality of an imported class? 2020-10-21T00:04:48.333Z+00:00 ... I don't think this answers the question, the OP is wondering how they can spy on a function, while the answer mocks the function. I could be wrong, however if you spy you keep ... More on stackoverflow.com
🌐 stackoverflow.com
March 6, 2019
How to spy same module function in jest?
209 How to mock imported named function in Jest when module is unmocked More on stackoverflow.com
🌐 stackoverflow.com
April 1, 2022
Cannot spy on individual functions that are individually exported
Having done a lot of research I cannot find a way to mock functions that are exported with no parent object. For example I'm trying to mock functions exported the following way: module.exports ... More on github.com
🌐 github.com
69
August 22, 2017
ecmascript 6 - Spying on an imported function that calls another function in Jest - Stack Overflow
But due to the fact that the OP ... for this specific requirement its also important. As matter of fact what we are discussing here is also stated on the jest issue I referred ;) 2018-06-14T16:41:23.423Z+00:00 ... The problem you describe is referenced on a jest issue. A possible solution to your problem (if you want to keep the functions inside the ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
JavaScript in Plain English
javascript.plainenglish.io › jest-spy-on-an-exported-function-d8fc91793876
Jest Spy on an Exported Function. The spyOn utility in Jest is incredibly… | by Shaurya Kalia | JavaScript in Plain English
April 2, 2024 - You might wonder how to correctly use jest.spyOn to monitor this function, especially what argument to pass first. Jest’s spyOn expects an object or module as the first parameter, and the name of the method to spy on as the second. The trick to effectively monitoring a named export is to import the entire module’s contents as an object, then pass this object into jest.spyOn.
🌐
Medium
medium.com › @DavideRama › mock-spy-exported-functions-within-a-single-module-in-jest-cdf2b61af642
Mock/Spy exported functions within a single module in Jest | by Davide Ramaglietta | Medium
February 14, 2020 - One of these functions depends on another function of the same module. export function foo () { ... } export function bar () { foo() } You want to assert that when executing bar() , it will also fire the execution of foo(). This would seem to be a classic situation for using Jest functionalities spyOn or mock. Therefore, you would expect to be able to write a test something like this: import * as myModule from './myModule';test('calls myModule.foo', () => { const fooSpy = jest.spyOn(myModule, 'foo');myModule.bar();expect(fooSpy).toHaveBeenCalledTimes(1); }); Surprisingly or not, this test would fail with the message Expected mock function to have been called one time, but it was called zero times.: You could try using jest.mock() or any other Jest interface to assert that your bar method depends on your foo method.
🌐
Code with Hugo
codewithhugo.com › jest-mock-spy-module-import
Jest Full and Partial Mock/Spy of CommonJS and ES6 Module Imports · Code with Hugo
October 15, 2019 - import db from './db'; const keyPrefix = 'todos'; export const makeKey = key => `${keyPrefix}:${key}`; export function getTodo(id) { return db.get(makeKey(id)); } Code listing lifted from examples/spy-internal-calls-esm/lib.named-export.js, tests showing there’s no simple way to mock/spy on makeKey are at examples/spy-internal-calls-esm/lib.named-export.jest-test.js
🌐
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 - ... check if a function was called correctly with Jest we use the expect() function with specific matcher methods to create an assertion....
🌐
Mercedes Bernard
mercedesbernard.com › blog › jest-mocking-strategies
Jest Mocking Strategies | Mercedes Bernard
July 12, 2020 - To mock getValue, we use a default ... the module name as a namespace), spy on the imported module's default property, and then chain a mock implementation to the returned mock function....
🌐
Jest
jestjs.io › the jest object
The Jest Object · Jest
May 7, 2026 - The second argument can be used ... of using Jest's automocking feature: ... When using the factory parameter for an ES6 module with a default export, the __esModule: true property needs to be specified. This property is normally generated by Babel / TypeScript, but here it needs to be set manually. When importing a default export, it's an instruction to import the property named default from ...
Find elsewhere
🌐
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 - First, we're importing our module as a namespace import. import * as esmModule from "./esmModule"; Then when we want to spy on the default export, we use "default": jest .spyOn(esmModule, "default") .mockImplementation(() => "mock implementation default"); Sometimes when trying to call jest.spyOn() with a third-party package, you'll get an error like the one below: TypeError: Cannot redefine property: useNavigate at Function.defineProperty (<anonymous>) When you run into this error, you'll need to mock the package that is causing the issue: import * as reactRouterDOM from "react-router-dom"; /
Top answer
1 of 2
11

You can mock the module like this:

import calculate from '../../calculate'
jest.mock('../xyz', ()=> () => Promise.resolve('mocked value'))

it('does something', async()=>{
  const op = await calculate()
  expect(op).toBe('mocked value')
})

if you need different return values from your mock you need to mock the module so it returns a spy. Then you have to import the module and you can set the return value during your tests:

import calculate from '../../calculate'
import myModule from '../xyz'
jest.mock('../xyz', ()=> jest.fn())

it('does something', async() => {
  myModule.mockImplementation(() => () =>  Promise.resolve('mocked value'))

  const op = calculate()
  expect(op).toBe('mocked value')
})

it('does something else', async() => {
  myModule.mockImplementation(() => () =>  Promise.resolve('another value'))
  const op = await calculate()
  expect(op).toBe('another value')
})


it('does fail', async() => {
  myModule.mockImplementation(() => () =>  Promise.reject('some Error')
  try{
    const op = await calculate()
  }catch (e){
    expect(e).toBe('some Error')
  }
})

2 of 2
0

There's no need to mock, which is something of a broad sword, since it works at the module level. Jest's spyOn is a more focussed way of doing this, since it is at the method level.

The confusion here is solely because of the internal workings of 'xyz'. You have assumed that the module called 'xyz' has a function within it also called 'xyz'. Hence Jest fails to find it.

If we assume that 'xyz' is actually the default export of the 'xyz' module, we can test using this:

const mock = jest.spyOn(myModule, 'default')

All of the rest of your test code is perfect:

mock.mockReturnValue('mocked value')
const op = calculate()
expect(op).toBe('mocked value')
🌐
GitHub
gist.github.com › gadflying › 5f2bf3c53370a0ceda5108816aedd298
[How to mock imported named function in Jest when module is unmocked] #jest #reactTestLib · GitHub
// myModule.test.js jest.mock('./myModule.js', () => ( { ...(jest.requireActual('./myModule.js')), otherFn: jest.fn() } )) import { otherFn } from './myModule.js' describe('test category', () => { it('tests something about otherFn', () => { otherFn.mockReturnValue('foo') expect(otherFn()).toBe('foo') }) }) // myModule.js export function otherFn() { console.log('do something'); } export function testFn() { otherFn(); // do other things } As shown above, it exports some named functions and importantly testFn uses otherFn.
🌐
Cursor AI
emgoto.com › mocking-with-jest
A guide to mocking functions and modules with Jest
December 21, 2025 - For example, you can assert to see what a function returns, or how many times it is called, without actually having to mock the function. However it doesn’t work too well with ES6 modules, and to be honest I don’t use it at all. This is because its intended usage is with CommonJS’s require: const time = require('./time'); const spy = jest.spyOn(time, 'getTime'); You see that you need to pass in two arguments to spyOn, one for the import object and one for the method name.
Top answer
1 of 2
2

Ideally you should test function independent. One test is not responsible for another function test functionality.

Not a best approach but you could do something like this:

util.js

export function add(a, b) {
  return a + b;
}

export function showMessage(a, b, addNew = add) {
  let sum = addNew(a, b);
  return `The sum is ${sum}`;
}

And in your test you could do like this: util.test.js

import * as Logics from "./util";

describe("showMessage", () => {
  it("should return message with sum", () => {
    let addSpy = jest.spyOn(Logics, "add");
    addSpy.mockReturnValue(123);
    let showMessageResponse = Logics.showMessage(2, 2, addSpy);
    expect(addSpy).toHaveBeenCalledTimes(1);
    expect(showMessageResponse).toBe(`The sum is 123`);
  });
});


Here is the sandbox you can play with: https://codesandbox.io/s/jest-test-forked-9zk1s4?file=/util.test.js:0-366

2 of 2
2

On short you can't really achieve it without changing your exports at all. You can read the reasons (and maybe other options) on this answer as well as this answer.

A better option imo would be something like (in your logics.js file):

import * as Logics from './logics;

and in showMessage function use it like you did in your second example:

  const sum = Logics.add(a, b)

Basically just importing everything in your logics.js and using that value in order to get the reference to the same add function.

Additional explanation: While you are mocking correctly the add, that is not the same function as the one called in showMessage and you basically can't mock that function (You can also check this code for proof

describe("showMessage", () => {
  it("should return the mocked sum (PASSES)", () => {
    jest.spyOn(Logics, "add").mockReturnValue(123);
    const showMessageResponse = Logics.add(2, 2);
    expect(showMessageResponse).toBe(123);
  });

  it("should return message with sum (FAILS)", () => {
    let addSpy = jest.spyOn(Logics, "add").mockReturnValue(123);
    const showMessageResponse = Logics.showMessage(2, 2);
    expect(addSpy).toHaveBeenCalledTimes(0);
    expect(showMessageResponse).toBe(`The sum is 123`);
  });
});

) also posted in this sandbox

🌐
GitHub
github.com › HugoDF › mock-spy-module-import
GitHub - HugoDF/mock-spy-module-import: JavaScript import/require module testing do's and don'ts with Jest
import * as db from './db'; const keyPrefix = 'todos'; const makeKey = key => `${keyPrefix}:${key}`; let autoId = 1; export function addTodo(todo) { const id = autoId++; const insertable = { ...todo, id }; return db.set(makeKey(id), insertable); } export function getTodo(id) { return db.get(makeKey(id)); } The calls to db.set and db.get can be spied/mocked using the following approach (full code test file at examples/spy-module-esm-named/lib.jest-test.js):
Starred by 56 users
Forked by 11 users
🌐
GitHub
github.com › jasmine › jasmine › issues › 1414
Cannot spy on individual functions that are individually exported · Issue #1414 · jasmine/jasmine
August 22, 2017 - import {thing} from 'emvio-util-responses; //call some function that calls thing() spyOn(???, 'thing').and.returnValue({}); expect(???.thing).toHaveBeenCalled(); I have tried many ways of accomplishing this but the mock is not called. Some suggest importing * and providing an alias as a parent object.
Author   jasmine
Top answer
1 of 1
1

Your updated implementation fails because the code under test is no longer using the fs module object your test is spying on - the named import brings in the relevant function directly. However this tells you a few things:

  • Firstly, that it's not a useful test - tests should give you the confidence to refactor your implementation, but here a behaviour-preserving change gives a false positive failing test; and
  • Secondly, that the code doesn't work - if the real statSync returns undefined, surely the function should return false (or at least throw a more informative error)?

Using jest.spyOn(fs, 'statSync') means your test is coupled to the implementation detail that the code it's testing uses import fs from 'node:fs'. To successfully mock the whole fs module instead, you need to refer to Module mocking in ESM. Applying this guidance to your specific case:

Copyimport { jest } from '@jest/globals';

const mock = jest.fn().mockReturnValue({ isDirectory: () => true });

// 1. need to use (unstable!) ES module mocking
jest.unstable_mockModule('node:fs', () => {
  const module = { statSync: mock };
  // 2. to tolerate default or named import, provide both
  return { default: module, ...module };
});

// 3. module needs dynamically importing _after_ mock is registered
const { myFunc } = await import('./my-func.js');

it('should work', () => {
  expect(myFunc('/test')).toBeTruthy();

  expect(mock).toHaveBeenCalled();
});

Note that it's not always the case that the default export is an object containing all of the named exports; as always, it's important to ensure that the test double has the same interface as the thing it's replacing.

This test will now pass with either implementation (using named or default export to access statSync).


However, given what you're trying to test, another way to test it (that depends on even fewer implementation details - you can now use methods other than statSync if desired) is to actually try it on the local file system. For example, assuming it's in the root of a conventional npm project (alternatively you could use a test fixtures directory with a known setup):

Copyimport { myFunc } from "./my-func.js";

it('should work for a directory', () => {
  expect(myFunc('./node_modules')).toBe(true);
});

it('should work for a file', () => {
  expect(myFunc('./package.json')).toBe(false);
});

it('should work for a missing object', () => {
  expect(myFunc('./missing')).toBe(false);
  // or something like:
  // expect(() => myFunc('./missing')).toThrow(/could not be found/);
});

As noted above, this shows that there's one case where the behaviour probably isn't correct:

Copy FAIL  ./my-func.test.js
  ✓ should work for a directory (1 ms)
  ✓ should work for a file
  ✕ should work for a missing object (1 ms)

  ● should work for a missing object

    TypeError: Cannot read properties of undefined (reading 'isDirectory')
🌐
Jest
jestjs.io › mock functions
Mock Functions · Jest
May 7, 2026 - Mock functions are also known as "spies", because they let you spy on the behavior of a function that is called indirectly by some other code, rather than only testing the output.
🌐
DhiWise
dhiwise.com › post › grow-testing-efficiency-with-jest-spyon-for-default-exports
A Deep Dive into Jest spyOn for Default Exports
April 30, 2025 - The spyOn function in Jest is used to monitor the calls made to a function, providing the ability to check how many times and with what arguments the function was called. It's an essential tool in a developer's testing library arsenal.