There are a few different ways to approach it.


You can mock only foo using jest.spyOn and something like mockImplementation:

import { MyClass } from './MyClass';
import * as FooFactory from './somewhere/FooFactory';

describe('test MyClass', () => {
  test('construct', () => {
    const mock = jest.spyOn(FooFactory, 'foo');  // spy on foo
    mock.mockImplementation((arg: string) => 'TEST');  // replace implementation

    const c = new MyClass('test');
    expect(c).toBeDefined();
    expect(c.getState()).toEqual('TEST');  // SUCCESS

    mock.mockRestore();  // restore original implementation
  });
});

Similarly, you can auto-mock FooFactory with jest.mock, then provide an implementation for foo:

import { MyClass } from './MyClass';
import * as FooFactory from './somewhere/FooFactory';

jest.mock('./somewhere/FooFactory');  // auto-mock FooFactory

describe('test MyClass', () => {
  test('construct', () => {
    const mockFooFactory = FooFactory as jest.Mocked<typeof FooFactory>;  // get correct type for mocked FooFactory
    mockFooFactory.foo.mockImplementation(() => 'TEST');  // provide implementation for foo

    const c = new MyClass('test');
    expect(c).toBeDefined();
    expect(c.getState()).toEqual('TEST');  // SUCCESS
  });
});

You can also mock FooFactory using a module factory passed to jest.mock:

import { MyClass } from './MyClass';

jest.mock('./somewhere/FooFactory', () => ({
  foo: () => 'TEST'
}));

describe('test MyClass', () => {
  test('construct', () => {
    const c = new MyClass('test');
    expect(c).toBeDefined();
    expect(c.getState()).toEqual('TEST');  // SUCCESS
  });
});

And finally, if you plan to use the same mock across multiple test files you can mock the user module by creating a mock at ./somewhere/__mocks__/FooFactory.ts:

export function foo(arg: string) {
  return 'TEST';
}

...then call jest.mock('./somewhere/FooFactory'); to use the mock in the test:

import { MyClass } from './MyClass';

jest.mock('./somewhere/FooFactory');  // use the mock

describe('test MyClass', () => {
  test('construct', () => {
    const c = new MyClass('test');
    expect(c).toBeDefined();
    expect(c.getState()).toEqual('TEST');  // SUCCESS
  });
});
Answer from Brian Adams on Stack Overflow
🌐
Jest
jestjs.io › mock functions
Mock Functions · Jest
May 7, 2026 - 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 ...
🌐
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 - When we call jest.mock("./cjsFunction"), this replaces the module (the file and all of its exports) with an auto-mock (docs). When an auto-mock is called, it will return undefined. However, it will provide methods for overriding the mock's implementation, return value, and more. You can see all the properties and methods it provides in the Jest Mock Functions documentation.
Discussions

typescript - How to mock a function in Jest - Stack Overflow
How do I mock the foo function used inside MyClass so that this test passes? ... There are a few different ways to approach it. You can mock only foo using jest.spyOn and something like mockImplementation: More on stackoverflow.com
🌐 stackoverflow.com
I fell into a hole setting up fetch mocking in Jest one too many times so I wrote this guide to save you time and frustration
mocking fetch is bad design. Wrap your api calls in thin functions your own, then mock those functions. mocking any function you dont own is bad design. More on reddit.com
🌐 r/javascript
53
262
February 29, 2020
How To Mock Fetch in Jest
you can mock it like any other module. jest.mock(PATH_TO_MODULE, () => { return yourMock } More on reddit.com
🌐 r/javascript
5
0
May 17, 2020
Jest Unit Testing Mocking Questions

It's something of a philosophical question. The finest unit tests you can write test only your own code and not much else. The coarsest acceptance test runs your program in a production environment and invokes it via its interface. Between the two there are many levels of testing, but what to call them and which you should use is heavily context and opinion dependent. If you want to use the real moment.js, go nuts. I'd probably do that, too. I do advise not using the real system clock, though. Time-dependent tests can be fragile.

More on reddit.com
🌐 r/learnprogramming
2
3
April 24, 2020
🌐
Jest
jestjs.io › the jest object
The Jest Object · Jest
May 7, 2026 - ... Returns a mock module instead of the actual module, bypassing all checks on whether the module should be required normally or not. Registers a callback function that is invoked whenever Jest generates a mock for a module.
🌐
Jest-bot
jest-bot.github.io › jest › docs › mock-functions.html
Mock Functions · Jest
When you need to recreate a complex behavior of a mock function such that multiple function calls produce different results, use the mockImplementationOnce method: var myMockFn = jest.fn() .mockImplementationOnce(cb => cb(null, true)) .mockImplementationOnce(cb => cb(null, false)); myMockFn((err, val) => console.log(val)); > true myMockFn((err, val) => console.log(val)); > false
🌐
Jest
jestjs.io › manual mocks
Manual Mocks · Jest
May 7, 2026 - Since we'd like our tests to avoid actually hitting the disk (that's pretty slow and fragile), we create a manual mock for the fs module by extending an automatic mock. Our manual mock will implement custom versions of the fs APIs that we can build on for our tests: ... Now we write our test. In this case jest.mock('fs') must be called explicitly, because fs is Node’s built-in module:
🌐
W3Resource
w3resource.com › jest › mock-functions.php
Jest Mock Functions
July 12, 2024 - Learn how to effectively use mock functions in Jest for testing, including mocking modules, custom implementations, and using matchers to verify function calls.
Top answer
1 of 1
80

There are a few different ways to approach it.


You can mock only foo using jest.spyOn and something like mockImplementation:

import { MyClass } from './MyClass';
import * as FooFactory from './somewhere/FooFactory';

describe('test MyClass', () => {
  test('construct', () => {
    const mock = jest.spyOn(FooFactory, 'foo');  // spy on foo
    mock.mockImplementation((arg: string) => 'TEST');  // replace implementation

    const c = new MyClass('test');
    expect(c).toBeDefined();
    expect(c.getState()).toEqual('TEST');  // SUCCESS

    mock.mockRestore();  // restore original implementation
  });
});

Similarly, you can auto-mock FooFactory with jest.mock, then provide an implementation for foo:

import { MyClass } from './MyClass';
import * as FooFactory from './somewhere/FooFactory';

jest.mock('./somewhere/FooFactory');  // auto-mock FooFactory

describe('test MyClass', () => {
  test('construct', () => {
    const mockFooFactory = FooFactory as jest.Mocked<typeof FooFactory>;  // get correct type for mocked FooFactory
    mockFooFactory.foo.mockImplementation(() => 'TEST');  // provide implementation for foo

    const c = new MyClass('test');
    expect(c).toBeDefined();
    expect(c.getState()).toEqual('TEST');  // SUCCESS
  });
});

You can also mock FooFactory using a module factory passed to jest.mock:

import { MyClass } from './MyClass';

jest.mock('./somewhere/FooFactory', () => ({
  foo: () => 'TEST'
}));

describe('test MyClass', () => {
  test('construct', () => {
    const c = new MyClass('test');
    expect(c).toBeDefined();
    expect(c.getState()).toEqual('TEST');  // SUCCESS
  });
});

And finally, if you plan to use the same mock across multiple test files you can mock the user module by creating a mock at ./somewhere/__mocks__/FooFactory.ts:

export function foo(arg: string) {
  return 'TEST';
}

...then call jest.mock('./somewhere/FooFactory'); to use the mock in the test:

import { MyClass } from './MyClass';

jest.mock('./somewhere/FooFactory');  // use the mock

describe('test MyClass', () => {
  test('construct', () => {
    const c = new MyClass('test');
    expect(c).toBeDefined();
    expect(c.getState()).toEqual('TEST');  // SUCCESS
  });
});
Find elsewhere
🌐
Medium
medium.com › @rickhanlonii › understanding-jest-mocks-f0046c68e53c
Understanding Jest Mocks. Explaining the Mock Function… | by Rick Hanlon II | Medium
July 13, 2018 - The most basic strategy for mocking is to reassign a function to the Mock Function. Then, anywhere the reassigned functions are used, the mock will be called instead of the original function: This type of mocking is less common for a couple reasons: jest.mock does this automatically for all functions in a module
🌐
Jest
jestjs.io › es6 class mocks
ES6 Class Mocks · Jest
May 7, 2026 - We'll mock SoundPlayer in our tests for SoundPlayerConsumer. ... Calling jest.mock('./sound-player') returns a useful "automatic mock" you can use to spy on calls to the class constructor and all of its methods.
🌐
Medium
james-dockeray.medium.com › manual-mocks-in-jest-c4d00f415b3b
Manual Mocks in Jest. Level up your unit tests | by James Dockeray | Medium
August 22, 2022 - Mocking a module sets the module’s properties to a mock function object. However, we need a way to access this object. To access the mock function object, import the mocked module at the top of the file. import track from "../lib/track"jest.mock("../lib/track")
🌐
Cursor AI
emgoto.com › mocking-with-jest
A guide to mocking functions and modules with Jest
December 21, 2025 - Mock the module with .mock() at the top of your test file, and then mock your desired function with jest.fn()
🌐
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
In Jest mocking is supported out ... has built-in mock functions that allow you to replace the actual implementation of a function, capture calls to a function, and verify parameters passed....
🌐
Bitovi
bitovi.com › blog › mocking-modules-in-jest-tests
Mocking Modules in Jest Tests
August 6, 2024 - The examples only include lines of code that are relevant to what is being described. When you need to mock a single function that is the value of a variable—e.g., a const or an argument to another function —use jest.fn.
🌐
pawelgrzybek
pawelgrzybek.com › mocking-functions-and-modules-with-jest
Mocking functions and modules with Jest | pawelgrzybek.com
April 12, 2020 - The simplest and most common way of creating a mock is jest.fn() method. If no implementation is provided, it will return the undefined value. There is plenty of helpful methods on returned Jest mock to control its input, output and implementation.
🌐
Netlify
jest-preview.netlify.app › docs › en › 22.x › mock-function-api
Mock Functions · Jest
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.
🌐
Medium
medium.com › trendyol-tech › jest-mocking-part-1-functions-1db67c033254
Jest Mocking — Part 1: Function by Enes Başpınar | Trendyol Tech
January 18, 2023 - We create the data manually and then test the function gives the expected result with this data. We don’t want to use the real value because data can be difficult to find, and our test can become fragile with API-related problems. Now we can continue with Jest. We use jest.fn(implementation?) to create a mock function.
🌐
GitHub
github.com › teamradhq › learning-jest-mocks
GitHub - teamradhq/learning-jest-mocks: Examples of common methods used to mock test fixtures within the Jest testing framework · GitHub
This collection contains a number of unit tests that demonstrate mocking in Jest. It can be used as a guide to learn how to work with mocks when testing. ... 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 with new, and allowing test-time configuration of return values.
Author   teamradhq
🌐
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.
🌐
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 spyOn function. The API for this function seems to be exactly what we need for our use case, as it accepts an entire module and the particular export that should ...