0
# Jest Mock Console
1
2
Jest Mock Console is a Jest testing utility that enables developers to mock console methods (log, warn, error) during test execution to prevent console output from cluttering test reports while still allowing verification that console methods were called with expected arguments.
3
4
## Package Information
5
6
- **Package Name**: jest-mock-console
7
- **Package Type**: npm
8
- **Language**: JavaScript/TypeScript
9
- **Installation**: `npm install --save-dev jest-mock-console`
10
11
## Core Imports
12
13
```typescript
14
import mockConsole from "jest-mock-console";
15
```
16
17
For CommonJS:
18
19
```javascript
20
const mockConsole = require("jest-mock-console");
21
```
22
23
With TypeScript types:
24
25
```typescript
26
import mockConsole, { RestoreConsole } from "jest-mock-console";
27
```
28
29
## Basic Usage
30
31
### Manual Console Restoration
32
33
```typescript
34
import mockConsole from "jest-mock-console";
35
36
describe("My tests", () => {
37
it("should mock console output", () => {
38
const restoreConsole = mockConsole();
39
40
console.error("This will not show in test output");
41
console.log("This will also not show");
42
43
expect(console.error).toHaveBeenCalledWith("This will not show in test output");
44
expect(console.log).toHaveBeenCalledWith("This will also not show");
45
46
restoreConsole(); // Restore original console
47
});
48
});
49
```
50
51
### Automatic Console Restoration with Setup Framework
52
53
Jest configuration (jest.config.js):
54
55
```javascript
56
module.exports = {
57
setupFilesAfterEnv: ["jest-mock-console/dist/setupTestFramework.js"]
58
};
59
```
60
61
Then in tests:
62
63
```typescript
64
import mockConsole from "jest-mock-console";
65
66
describe("My tests", () => {
67
it("should mock console output", () => {
68
mockConsole(); // No need to call restore function
69
70
console.error("This will not show in test output");
71
expect(console.error).toHaveBeenCalledWith("This will not show in test output");
72
73
// Console automatically restored after each test
74
});
75
});
76
```
77
78
## Architecture
79
80
Jest Mock Console is designed to work with different Jest test runner environments:
81
82
- **Jest Globals Detection**: Automatically detects if Jest globals are available and requires them if needed
83
- **Test Runner Compatibility**: Supports both Jasmine (Jest < 27) and Circus (Jest >= 27) test runners
84
- **Console State Management**: Preserves original console state and restores it after mocking
85
- **Flexible Mocking Strategy**: Supports selective mocking (specific methods) or complete mocking (all console methods)
86
87
The setup test framework provides automatic console restoration by hooking into Jest's test lifecycle:
88
- **Jasmine Mode**: Uses `jasmine.getEnv().describe` to inject cleanup hooks
89
- **Circus Mode**: Decorates global `describe` functions and their variants (`skip`, `only`, `each`)
90
- **Lifecycle Hooks**: Automatically adds `beforeEach`/`afterEach` and `beforeAll`/`afterAll` hooks for console restoration
91
92
## Capabilities
93
94
### Console Mocking Function
95
96
Main function that mocks console methods and returns a restore function.
97
98
```typescript { .api }
99
/**
100
* Mock console methods to prevent output during tests
101
* @param mockArg - Determines which console methods to mock and how
102
* @returns Function to restore original console
103
*/
104
declare function mockConsole(): RestoreConsole;
105
declare function mockConsole(mockArg: ConsoleProps): RestoreConsole;
106
declare function mockConsole(mockArg: ConsoleProps[]): RestoreConsole;
107
declare function mockConsole(mockArg: MockObj): RestoreConsole;
108
109
export default mockConsole;
110
111
type ConsoleProps = keyof Console;
112
type MockObj = {[key in ConsoleProps]?: Console[key]};
113
type RestoreConsole = () => void;
114
```
115
116
**Parameter Options:**
117
118
- **No argument**: Mocks default console methods ['log', 'warn', 'error'] with jest.fn()
119
- **String**: Mocks a single console method (e.g., 'error')
120
- **Array**: Mocks multiple console methods (e.g., ['log', 'warn'])
121
- **Object**: Provides custom implementations for console methods
122
123
**Usage Examples:**
124
125
```typescript
126
import mockConsole from "jest-mock-console";
127
128
// Mock default methods (log, warn, error)
129
const restore1 = mockConsole();
130
131
// Mock only error method
132
const restore2 = mockConsole("error");
133
134
// Mock specific methods
135
const restore3 = mockConsole(["error", "warn"]);
136
137
// Custom implementations
138
const restore4 = mockConsole({
139
error: (msg: string) => `Error: ${msg}`,
140
warn: (msg: string) => `Warning: ${msg}`
141
});
142
143
// Always restore when done
144
restore1();
145
restore2();
146
restore3();
147
restore4();
148
```
149
150
### Setup Test Framework
151
152
Automatic console restoration between tests when included in Jest configuration.
153
154
**Configuration:**
155
156
```javascript
157
// jest.config.js
158
module.exports = {
159
setupFilesAfterEnv: ["jest-mock-console/dist/setupTestFramework.js"]
160
};
161
```
162
163
**Features:**
164
165
- Automatically restores console between `it()` blocks
166
- Supports both Jasmine (Jest < 27) and Circus (Jest >= 27) test runners
167
- Works with `describe`, `describe.skip`, `describe.only`, and `describe.each`
168
- Provides `beforeEach`/`afterEach` and `beforeAll`/`afterAll` hooks for restoration
169
170
**Behavior:**
171
172
- Saves original console state before each test
173
- Restores console state after each test completes
174
- No manual restoration required when using `mockConsole()`
175
176
### Mock Verification
177
178
Since console methods are mocked with `jest.fn()`, you can use standard Jest assertions:
179
180
```typescript
181
import mockConsole from "jest-mock-console";
182
183
describe("Console verification", () => {
184
it("should verify console calls", () => {
185
const restoreConsole = mockConsole();
186
187
console.error("Test error message");
188
console.log("Test log message");
189
190
// Verify calls
191
expect(console.error).toHaveBeenCalledWith("Test error message");
192
expect(console.error).toHaveBeenCalledTimes(1);
193
expect(console.log).toHaveBeenCalledWith("Test log message");
194
195
// Verify all calls
196
expect(console.error.mock.calls).toEqual([["Test error message"]]);
197
198
restoreConsole();
199
});
200
});
201
```
202
203
## Types
204
205
Complete TypeScript type definitions for the package.
206
207
```typescript { .api }
208
type DefaultConsole = Console;
209
210
type ConsoleProps = keyof DefaultConsole;
211
212
type MockObj = {[key in ConsoleProps]?: DefaultConsole[key]};
213
214
type RestoreConsole = () => void;
215
216
declare module 'jest-mock-console' {
217
export default function MockConsole(): RestoreConsole;
218
export default function MockConsole(mockArg: ConsoleProps): RestoreConsole;
219
export default function MockConsole(mockArg: ConsoleProps[]): RestoreConsole;
220
export default function MockConsole(mockArg: MockObj): RestoreConsole;
221
}
222
```
223
224
## Common Use Cases
225
226
### Preventing Console Clutter in Tests
227
228
```typescript
229
describe("Component with console output", () => {
230
it("should not clutter test output", () => {
231
const restoreConsole = mockConsole();
232
233
// Component that logs internally
234
const component = new MyComponent();
235
component.debugInfo(); // Calls console.log internally
236
237
// Test passes without console output
238
expect(component.isInitialized).toBe(true);
239
240
restoreConsole();
241
});
242
});
243
```
244
245
### Testing Console Output
246
247
```typescript
248
describe("Logger component", () => {
249
it("should log error messages", () => {
250
const restoreConsole = mockConsole(["error"]);
251
252
const logger = new Logger();
253
logger.error("Something went wrong");
254
255
expect(console.error).toHaveBeenCalledWith("Something went wrong");
256
257
restoreConsole();
258
});
259
});
260
```
261
262
### Custom Console Behavior
263
264
```typescript
265
describe("Console redirection", () => {
266
it("should redirect console to custom handler", () => {
267
const logs: string[] = [];
268
const restoreConsole = mockConsole({
269
log: (msg: string) => logs.push(msg)
270
});
271
272
console.log("Test message");
273
274
expect(logs).toEqual(["Test message"]);
275
276
restoreConsole();
277
});
278
});
279
```