I ended up ditching the default export:

// UniqueIdGenerator.js
export const uniqueIdGenerator = () => Math.random().toString(36).substring(2, 8);

And then I could use and spy it like this:

import * as UniqueIdGenerator from './UniqueIdGenerator';
// ...
const spy = jest.spyOn(UniqueIdGenerator, 'uniqueIdGenerator');

Some recommend wrapping them in a const object, and exporting that. I suppose you can also use a class for wrapping.

However, if you can't modify the class there's still a (not-so-nice) solution:

import * as UniqueIdGenerator from './UniqueIdGenerator';
// ...
const spy = jest.spyOn(UniqueIdGenerator, 'default');
Answer from thisismydesign 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
Luckily, there is a simple way to solve this. To spy on an exported function in jest, you need to import all named exports and provide that object to the jest.spyOn function.
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
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
Spy on default exported function with Jest - javascript
import logger from '../../../s... default: jest.fn(loggerMod.default) }; }); ... expect(logger).toHaveBeenCalled(); Most times it's preferable to mock a function that does potentially undesirable side effects rather than spy on it, and this is much simpler, especially for a module with default export ... More on stackoverflow.com
🌐 stackoverflow.com
Allow to spy on modules that export functions
We can currently use jest.spyOn to spy on Node modules that are objects, which contain functions, but we can't use it to spy on Node modules that export functions. More on github.com
🌐 github.com
3
August 23, 2019
🌐
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 - When you spy on only the default export, you might encounter issues if the default export is not an object or a class instance. In such cases, you may need to employ workarounds or adjust your testing strategy. The main difference between a mock function and a spyOn function in Jest is that mocking completely replaces the function with a fake version, while spying wraps the actual function, allowing you to observe its behavior without changing its implementation.
🌐
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 - Jest Spy on an Exported Function The spyOn utility in Jest is incredibly versatile, enabling you to monitor, track, and even replace the behavior of functions. However, applying this to a named …
🌐
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 - 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.:
🌐
GitHub
github.com › jasmine › jasmine › issues › 1414
Cannot spy on individual functions that are individually exported · Issue #1414 · jasmine/jasmine
August 22, 2017 - You switched accounts on another tab or window. Reload to refresh your session. ... 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: ... import {thing} from 'emvio-util-responses; //call some function that calls thing() spyOn(???, 'thing').and.returnValue({}); expect(???.thing).toHaveBeenCalled();
Author   kevinlbatchelor
🌐
CopyProgramming
copyprogramming.com › howto › how-to-spy-on-a-default-exported-function-with-jest
How to Spy on a Default Exported Function with Jest: Complete 2026 Guide - Spy on a default exported function with jest complete
November 27, 2025 - The challenge with default exports is that they're not assigned to an object property you can directly access. When you import a default export like import myFunction from './utils', Jest doesn't have a conventional object property to spy on like it would with jest.spyOn(utils, 'myFunction').
🌐
kaliaverse
shauryakalia.com › jest-spy-on-an-exported-function-d8fc91793876
Jest Spy on an Exported Function - Shaurya Kalia
February 10, 2025 - The spyOn utility in Jest is incredibly versatile, enabling you to monitor, track, and even replace the behavior of functions. However, applying this to a named export from a module can be a bit tricky due to the specific parameters required by spyOn...
Find elsewhere
🌐
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

🌐
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'; const makeKey = key => `${keyPrefix}:${key}`; function getTodo(id) { return db.get(makeKey(id)); } const lib = { makeKey, getTodo }; export default lib; Tests showing there’s no simple way to mock/spy on makeKey are at examples/spy-internal-calls-esm/lib.default-export.jest-test.js.
🌐
GitHub
github.com › jestjs › jest › issues › 8870
Allow to spy on modules that export functions · Issue #8870 · jestjs/jest
August 23, 2019 - 🚀 Feature Proposal / Example Allow the following to work, in order to spy on modules that export functions (execa exports a function): const execa = require('execa'); jest.spyOn(global, &#3...
Author   garyking
🌐
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() method allows Jest to record calls to a method on an object and provide its own replacement. This only works on objects, and we can use it because our module is exporting an object that contains our function.
🌐
Stack Overflow
stackoverflow.com › questions › 51786777 › how-to-spy-on-an-exported-and-mocked-function-in-jest › 51788783
node.js - How To Spy On An Exported and Mocked Function In Jest - Stack Overflow
I would like to spy on the exported function to check that it was called with something. This is my code... import { addNewPaymentMethod } from '../src/service' jest.mock('../src/service', () => ({ addNewPaymentMethod : (paymentMethodInfoModel) => { let responseFromApi = {responseStatus:{name:'blah'}}; return Promise.resolve(responseFromApi); } })) import { createNewPaymentMethod } from '../src/actions/paymentMethod' test('test expect', () => { createNewPaymentMethod({owNickName:'nName',id:22})(); //this is the bit I don't know how to do //... jest.spyOn(addNewPaymentMethod); expect(addNewPaymentMethod).toBeCalledWith({some:object}); });
🌐
Stack Overflow
stackoverflow.com › questions › 57619182 › use-jest-spyon-on-an-exported-function-from-a-node-module
node.js - Use `jest.spyOn` on an exported function from a ...
const childProcess = require('child_process'); const spySpawnSync = jest.spyOn(childProcess, 'spawnSync').mockImplementation(); This allows us to use spySpawnSync to check what arguments it was last called with, like so: ... However, this is not possible with Node modules that export a function, such as with the execa package.
🌐
Mercedes Bernard
mercedesbernard.com › blog › jest-mocking-strategies
Jest Mocking Strategies | Mercedes Bernard
July 12, 2020 - To mock getValue, we use a default import to import the entire module's contents, spy on the imported module's example property (this is the named export), and then chain a mock implementation to the returned mock function. In this case, our mock implementation is a function that returns an object with a getValue property, just like in our previous example. import * as exampleModule from "../namedFunctionReturnObject"; const mockExpected = "mock value"; jest.spyOn(exampleModule, "example").mockImplementation(() => ({ getValue: jest.fn(() => mockExpected), })); it("returns the expected value", () => { const { getValue } = exampleModule.example(); const actual = getValue(); expect(actual).toEqual(mockExpected); });
🌐
Adoclib
adoclib.com › blog › how-to-spy-on-a-default-exported-function-with-jest.html
How To Spy On A Default Exported Function With Jest?
Mock/Spy exported functions within a single module in Jest. A brief guide on how to test that a function depends on another function exported by the same module.