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 ...
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
  });
});
Discussions

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
Is it possible to test a single function in jest?

It depends where getUser comes from, is it imported or defined in the file.

One option would be to inject the function you can do this:

// api.js
const request = (url, getUser = getUser) => {
  ...
}

Then in your test pass in a stub as the second argument.

More on reddit.com
🌐 r/reactjs
3
3
February 1, 2019
🌐
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.
🌐
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.
🌐
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.
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.
🌐
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.
🌐
Geshan
geshan.com.np › blog › 2023 › 11 › jest-mockimplementation
Jest mock implementation: A beginner’s guide to replacing function implementation for tests
November 25, 2023 - Jest Mock Implementation is a technique that lets you replace the internal logic of a function with a custom implementation during test execution. This can be immensely helpful in scenarios where you want to isolate a specific piece of code ...
🌐
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
Then, we’re overwriting the function that we want to mock functionToMock with a Jest mock function. This means that inside of our test environment, any calls to functionToMock from our code will not trigger the actual function but rather this jest mock function.
🌐
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")
🌐
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 › javascript-in-plain-english › how-to-mock-functions-classes-and-modules-with-jest-c724d0ffbf18
How to Mock Functions, Classes, and Modules With Jest | by Razvan Ludosanu | JavaScript in Plain English
July 27, 2024 - To override the implementation of a function, and consequently its behaviour, we can define its new implementation within the jest.fn() function itself, and test its result using the toHaveReturnedWith() matcher. const proxy = require('./proxy'); test('it should return the data length', () => { const mockFn = jest.fn(data => data && data.length || 0); proxy('Hello World', mockFn); expect(mockFn).toHaveReturnedWith(12); });
🌐
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