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
import { functionToMock } from '@module/api'; jest.spyOn(???, '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

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 ... 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
spy on pure functions exported as const
Whether or not you can spy on these functions depends on what module type your app is targeting. If it is ES6, you do a default export in your helper file and spy on the functions via spyOn(defaultImport, ‘helperFn’). You cannot just spy on the function itself, since ES6 modules export read-only references to their exposed values (i.e., you can’t overwrite the reference with a spy). If you target commonjs, you can get away with it because the references are not actually read-only at runtime. You need to spy on the reference before your component/service that you’re testing is initialized, so before the TestBed calls for example. At least, this is what my app has experienced recently. More on reddit.com
🌐 r/Angular2
11
2
March 12, 2021
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
🌐
Jest
jestjs.io › the jest object
The Jest Object · Jest
1 week ago - The jest object is automatically in scope within every test file. The methods in the jest object help create mocks and let you control Jest's overall behavior. It can also be imported explicitly by via import {jest} from '@jest/globals'.
🌐
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 - 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); });
🌐
Jest
jestjs.io › mock functions
Mock Functions · Jest
1 week ago - The mocked() helper method wraps types of the source object and its deep nested members with type definitions of Jest mock function. You can pass {shallow: true} as the options argument to disable the deeply mocked behavior. Returns the source object. song.ts · export const song = { one: { more: { time: (t: number) => { return t; }, }, }, }; song.test.ts · import {expect, jest, test} from '@jest/globals'; import {song} from './song'; jest.mock('./song'); jest.spyOn(console, 'log'); const mockedSong = jest.mocked(song); // or through `jest.Mocked<Source>` // const mockedSong = song as jest.Mo
🌐
Bitovi
bitovi.com › blog › mocking-modules-in-jest-tests
Mocking Modules in Jest Tests
August 6, 2024 - If you need to verify the invocation ... with any module export, such as a Class). The entire module must be imported into the test file—typically using the import * as module syntax....
🌐
Jest
jestjs.io › es6 class mocks
ES6 Class Mocks · Jest
(ES5 doesn't have arrow functions nor classes, so both will be transpiled to plain functions.) Lets say that you want to mock or spy on the method playSoundFile within the class SoundPlayer. A simple example: // your jest test file below · import SoundPlayer from './sound-player'; import SoundPlayerConsumer from './sound-player-consumer'; const playSoundFileMock = jest · .spyOn(SoundPlayer.prototype, 'playSoundFile') .mockImplementation(() => { console.log('mocked function'); }); // comment this line if just want to "spy" it('player consumer plays music', () => { const player = new SoundPlayerConsumer(); player.playSomethingCool(); expect(playSoundFileMock).toHaveBeenCalled(); }); Lets imagine our class SoundPlayer has a getter method foo and a static method brand ·
Find elsewhere
🌐
Medium
mdpuneethreddy.medium.com › jest-mock-functions-or-modules-using-typescript-99711d69a3bb
Jest: Mock functions or modules using typescript | by M D PUNEETH REDDY | Medium
July 22, 2022 - Next, we mock the function to return some mock value, write the tests, and check the output value. import * as utils from "../utils" describe("mock tests",()=>{ jest.spyOn(utils,"getNumber").mockReturnValueOnce(1) it("mock function inside another function",()=>{ expect(utils.printNumber()).toBe(1) }) })
🌐
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.
Author   kevinlbatchelor
🌐
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 * 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); ...
🌐
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
April 18, 2021 - Another approach to mock a particular function from an imported module is to use the jest.spyOn function.
🌐
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 - Learn how to spy on a React module's default export and test its implementation without affecting the actual implementation.
🌐
Reddit
reddit.com › r/angular2 › spy on pure functions exported as const
r/Angular2 on Reddit: spy on pure functions exported as const
March 12, 2021 -

Lately I've been writing pure functions more and more in my code, they convey meaning very well, are easy to write and test

Now that most of my logic is in pure function I tend to write them outside of components because they don't depend on the state of the component.

Example getUsername is pure and not used in the template and as such doesn't really need to be a method of the component.

@Component({selector: ..., templateUrl: ..., styleUrls: ...})
export class UserComponent implements OnInit {
    @Input() user: User;
    username: string

    ngOnInit() {
        this.username = getUsername(this.user);
    }
}

export const getUsername = (user: User): string => `${user.firstname} ${user.lastname}`;

When I have too many of these pure functions I sometimes move them to a helper file.

Everything works perfectly, except when I try to spy on them for unit testing. At this point jasmine refuses to spy on them (relevant github issue)

What do you guys think I should do ? Move my pure functions to method of components ? Change my helper files into services eventhough they don't use any state ?

I feel like I have to remove relevant information from my code (purity of the functions) for the sole reason of unit testing and I don't like it

Edit: spying on an exported function used to work but stopped working with Angular 9, cf this github issue

🌐
Cursor AI
emgoto.com › mocking-with-jest
A guide to mocking functions and modules with Jest
December 21, 2025 - If you wanted to replicate the behaviour of .spyOn() with ES6 module imports, you can use requireActual(): import { getTime } from './time'; jest.mock('./time', () => ({ getTime: jest.fn( jest.requireActual('./time').getTime ) })) ... But then ...
🌐
Developright
developright.co.uk › posts › mocking-functions-or-methods-with-jest.html
Mocking & Spying with Jest SpyOn | DevelopRight.co.uk
December 30, 2022 - If the tests are at unit test level then it makes sense to override the function because the file that you're originally testing should only be tested in isolation (when unit testing). // import package import randomLibrary from './libraries/random'; // inside test (shortened for brevity) jest.spyOn(randomLibrary, 'functionOrMethod');
🌐
Mercedes Bernard
mercedesbernard.com › blog › jest-mocking-strategies
Jest Mocking Strategies | Mercedes Bernard
July 12, 2020 - To mock getValue, we use a default import, spy on the imported object's getValue property, and then chain a mock implementation to the returned mock function. Because example is an object, we can spy on its properties. If we didn't want to mock the implementation, we could leave that part off and still be able to track that the returned mock function was called. * Note: jest.spyOn invokes the function's original implementation which is useful for tracking that something expected happened without changing its behavior.
🌐
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 Jest spyOn() documentation recommends resetting the state using jest.restoreAllMocks() in an afterEach() callback, which is what we did above. If we did not do this, the mock would return undefined in the next test after spyOn() was called. ES modules can have default and named exports: // esmModule.js export default function () { return "original default"; } export function named() { return "original named"; } Here's what the tests for the file above would look like: import * as esmModule from "./esmModule"; afterEach(() => { jest.restoreAllMocks(); }); it("can override the implementation
🌐
Meticulous
meticulous.ai › blog › how-to-use-jest-spyon
How to use Jest spyOn with React.js and Fetch
Jest’s spyOn method is used to spy on a method call on an object. It is also very beneficial in cases where the Jest mock module or mock function might not be the best tool for the job on hand.