Jest Mock Class Not Working Fix
In this tutorial, you'll learn about Jest Mock Class Not Working Fix. We cover key concepts, practical examples, and best practices.
Your mock class constructor doesn't return the expected instance — methods are undefined or the mock doesn't track calls as expected.
The Problem
// WRONG — mock doesn't replace the class correctly
class Database {
connect() { return 'connected'; }
query(sql) { return `result of ${sql}`; }
}
jest.mock('./Database'); // Auto-mock — methods return undefined
test('queries database', () => {
const db = new Database();
expect(db.query('SELECT 1')).toBe('result of SELECT 1'); // FAILS
});
Expected: "result of SELECT 1"
Received: undefined
Auto-mocked class methods return undefined by default. You need to set up return values or provide a manual mock.
Step-by-Step Fix
1. Provide a manual mock factory
// RIGHT — manual mock with implementation
jest.mock('./Database', () => {
return jest.fn().mockImplementation(() => ({
connect: jest.fn().mockReturnValue('connected'),
query: jest.fn().mockReturnValue('mock result'),
}));
});
test('queries database', () => {
const db = new Database();
expect(db.query('SELECT 1')).toBe('mock result');
});
2. Spy on prototype methods
// RIGHT — spy on class prototype
import Database from './Database';
beforeEach(() => {
jest.spyOn(Database.prototype, 'query').mockReturnValue('spy result');
});
afterEach(() => {
jest.restoreAllMocks();
});
test('uses prototype spy', () => {
const db = new Database();
expect(db.query('SELECT 1')).toBe('spy result');
});
3. Mock with constructor arguments
// RIGHT — mock that captures constructor args
const mockDb = jest.fn().mockImplementation((connectionString) => ({
connectionString,
connect: jest.fn(),
query: jest.fn(),
}));
jest.mock('./Database', () => mockDb);
test('creates with connection string', () => {
new Database('postgres://localhost/db');
expect(mockDb).toHaveBeenCalledWith('postgres://localhost/db');
});
4. Mock module that exports a class
// RIGHT — complete class mock
jest.mock('./Database', () => ({
Database: jest.fn().mockImplementation(() => ({
connect: jest.fn(),
disconnect: jest.fn(),
isConnected: false,
})),
}));
Expected output:
PASS tests/class.test.js
✓ queries database (7 ms)
✓ uses prototype spy (4 ms)
✓ creates with connection string (5 ms)
Prevention Tips
- Use factory functions in
jest.mock()for class mocks - Spy on
ClassName.prototype.methodfor individual method mocking - Capture constructor arguments for verification
- Use
jest.fn().mockImplementation()for full control - Reset mocks between tests with
jest.clearAllMocks()
Common Mistakes with mock class
- Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists - Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
These mistakes appear frequently in real-world JEST code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro