🪟 Windows TippsThe Gemini desktop app is now available for Windows(11.09.2026 um 17:06 Uhr)
⚠️ Malware / Trojaner / VirenWindows 11 just dropped the tool ransomware abused, Microsoft says don’t restore WMIC(10.09.2026 um 20:11 Uhr)
⚠️ Malware / Trojaner / VirenVorsicht: Android-Malware verschlüsselt Ihre Handys und nimmt heimlich Fotos auf(11.09.2026 um 09:35 Uhr)
🕵️ SicherheitslückenMicrosoft geht endlich eines der nervigsten Probleme von Windows 11 an(11.09.2026 um 11:58 Uhr)
💾 IT Security ToolsSysinternals Suite(11.09.2026 um 12:00 Uhr)
🕵️ SicherheitslückenDefender 0-Day ShieldBreak (CVE-2026-69414) nicht sauber gepatcht - BornCity(11.09.2026 um 12:52 Uhr)
🪟 Windows TippsThe Gemini desktop app is now available for Windows(11.09.2026 um 17:06 Uhr)
⚠️ Malware / Trojaner / VirenWindows 11 just dropped the tool ransomware abused, Microsoft says don’t restore WMIC(10.09.2026 um 20:11 Uhr)
⚠️ Malware / Trojaner / VirenVorsicht: Android-Malware verschlüsselt Ihre Handys und nimmt heimlich Fotos auf(11.09.2026 um 09:35 Uhr)
🕵️ SicherheitslückenMicrosoft geht endlich eines der nervigsten Probleme von Windows 11 an(11.09.2026 um 11:58 Uhr)
💾 IT Security ToolsSysinternals Suite(11.09.2026 um 12:00 Uhr)
🕵️ SicherheitslückenDefender 0-Day ShieldBreak (CVE-2026-69414) nicht sauber gepatcht - BornCity(11.09.2026 um 12:52 Uhr)

🔧 Programmierung 🕛 vor 1 Jahr 5 Min Lesezeit
0

Mocking with Jest and typescript - a cheatsheet

↗ Quelle (dev.to)
🗣️ Stimme:
📑 Inhaltsübersicht

Jest is great at mocking imports in javascript/typescript, but I find it very hard to remember implementation specifics.



Functions and objects need to be mocked in different ways, default exports are mocked subtly differently to named exports, and Jest doesn't work particularly well with typescript. Combine all these things and it can be hard to work out, or even search for, the correct approach for your mocking scenario.



I have created this guide to answer the question "How do I mock my import?" no matter what that import might be. Default or named, function or object.






My Environment



I have tested all of these approaches using the following versions of software:




  • node v22.11.0

  • jest v29.7.0

  • ts-jest v29.2.5

  • @types/jest v29.5.14



And with a default, minimal jest.config.js file:




CODE
export default {
testEnvironment: 'node',
transform: {
'^.+.tsx?$': ['ts-jest', {}],
},
testMatch: ['**/*.test.ts'],
};









Mocking Imports



Broadly common imports fall into two categories that we might want to mock:




  • functions

  • objects



We will tackle them both in turn, starting with functions.






Importing functions



Functions exported from modules can be named or default. We will look at both. First:






Mocking a named exported function from a module



This should be used to mock a named exported function from a module, something like this:




CODE
// ./path/to/module.ts

export function doSomething(...) {
...
}






It can be mocked like so:




CODE
import { doSomething } from './path/to/module';

// note: This should be the path to the module from the test file,
// NOT from the module that contains the doSomething function itself.
jest.mock('./path/to/module', () => ({
doSomething: jest.fn(),
}));

...

it('should do something', () => {
// We need to assert that the function is a jest.Mock
// so that typescript will allow us to call mock methods.
(doSomething as jest.Mock).mockReturnValue(mockValue);

// run your test here

expect(doSomething).toHaveBeenCalledTimes(1); // etc.
});









Mocking the default function returned from a module



This should be used to mock a function that is the default export from a module, something like this:




CODE
// ./path/to/module.ts

export default function doSomething(...) {
...
}






It is mocked similarly to named exports:




CODE
import doSomething from './path/to/module'

jest.mock('./path/to/module', () => ({
__esModule: true,
default: jest.fn()
}))

...

it('should do something', () => {
(doSomething as jest.Mock).mockResolvedValue(mockData);

// Run your test here

expect(doSomething).toHaveBeenCalledTimes(5);
});









Importing objects



There are a few variations to consider when mocking an exported object (be that a class, json object or otherwise).




  • Is it a named or default export?

  • Does it have methods we also wish to mock, or just properties?






Mocking default objects with no methods



If you just need to mock properties (a config file for example), not methods, then this is how to do it:




CODE
import config from '../config';

jest.mock('../config', () => ({
__esModule: true,
default: {
apiKey: '123MockKey',
...
},
}));

...

it('Should do something', () => {
...
});






And if the mocked properties need to vary per test:




CODE
import config from '../config';

const mockConfig = {
apiKey: '123MockKey',
...
};

jest.mock('../config', () => ({
__esModule: true,
default: mockConfig,
}));

...

beforeEach(() => {
// restore defaults before each test
mockConfig.apiKey = '123MockKey';
...
});

it('Should do something', () => {
mockConfig.apiKey = 'new value';

// rest of the test
});

// more tests









Mocking named export objects without methods



Very similar to mocking default export objects:




CODE
import { config } from '../config';

const mockConfig = {
apiKey: '123MockKey',
...
};

jest.mock('../config', () => ({
config: mockConfig,
}));

// the rest is exactly the same as when mocking a default export object.









Mocking an object with methods



When an object with methods is exported (named or default) from a module and we need to mock the output of those methods, the approach is slightly different.



Given a class:




CODE
// ./path/to/module.ts

class ComplicatedThing {
// properties, fields, constructor etc. go here

getData() {
...
}

...
}

// note: I don't necessarily recommend exporting an instance
// of a class like this - purely illustrative for testing purposes.
// https://medium.com/@lazlojuly/are-node-js-modules-singletons-764ae97519af
export const complicatedThing = new ComplicatedThing(...);






And to mock our exported object:




CODE
import { complicatedThing } from './path/to/module';

jest.mock('./path/to/module', () => ({
complicatedThing: {
getData: jest.fn()
}
}));

...

it('Should do something', () => {
(complicatedThing.getData as jest.Mock).mockReturnValue(mockData);

// run the test here

expect(complicatedThing.getData).toHaveBeenCalledWith(...);
});






Mocking a default export object is exactly the same except when we define the mock:




CODE
jest.mock('./path/to/module', () => ({
__esModule: true,
default: {
getData: jest.fn()
},
}));









Bonus: Mocking methods on an object passed directly to a test function/class as a parameter



This is for mocking an object that is not directly imported into a module you're testing, but is instead passed in as a parameter to a class/function.



Note: If you are mocking a class, you might instead wish to create an interface and create a mock implementation of that to pass into your function/class. This will save you needing to do inelegant type assertion shenanigans as below.




CODE
// ./path/to/module

export class ComplicatedThing {
// properties and constructor etc.

getData(...) { ... }

updateData(...) { ... }
}









CODE
// .path/to/doSomething
import { ComplicatedThing } from './path/to/module';

export function doSomething(myComplicatedThing: ComplicatedThing) {
...
}









CODE
import { ComplicatedThing } from './path/to/module';
import { doSomething } from './path/to/doSomething';

const mockGetData = jest.fn();
const mockUpdateData = jest.fn();

// typescript shenanigans - asserting that it IS a given type will
// allow us to pass that into functions as a parameter of that type.
const mockComplicatedThing = {
getData: mockGetData,
updateData: mockUpdateData
} as unknown as ComplicatedThing;

...

it('Should do something', () => {
mockGetData.mockReturnValue(mockData);
mockUpdateData.mockReturnValue(moreMockData);

const response = doSomething(mockComplicatedThing);

expect(mockUpdateData).toHaveBeenCalledWith(...);
});









Conclusion



I hope this will be useful to you, and to my future self when I next struggle to remember the details for how to mock imports in typescript.



I hope that it can cover all of your simple mocking needs, and give you a place to begin when mocking more complex imports.



Thanks for reading.

Vollständiger Original-Bericht
Ausführliche Details, Code-Beispiele & Hersteller-Stellungnahme auf dev.to.
↗ Original-Artikel auf dev.to lesen
Wie bewertest du diesen Beitrag?
1 Klick Feedback
Teilen mit Netzwerk & Team:

Community-Analysen & Experten-Meinungen 0

Verfasse deine eigene Analyse, teile Workarounds oder diskutiere diesen Vorfall im Blog.
Noch keine Community-Analyse verfasst. Markiere einen Textabschnitt oder klicke oben auf Eigene Analyse verfassen“!
Community Pulse: Relevanz-Einschätzung
1 Klick Experten-Votum
🔴 Akute Relevanz 0%
🟡 In Evaluierung 0%
🟢 Keine Auswirkung 0%
Spannende Innovation 0%
Verwandte Story-Cluster & Quellen (Vektor-KI)
Port 8095 Engine
1 Quelle
The Gemini desktop app is now available for Windows
1 Quelle
Windows 11 just dropped the tool ransomware abused, Microsoft says don’t restore WMIC
1 Quelle
Vorsicht: Android-Malware verschlüsselt Ihre Handys und nimmt heimlich Fotos auf
Ähnliche Beiträge
🔍 Verwandte News

Auch interessante Nachrichten Mocking with Jest and typescript - a cheatsheet

Thematisch verwandte Begriffe: Mocking, with, Jest, typescript · 6 Treffer

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...