Add custom message to Jest expects
npx @tessl/cli install tessl/npm-jest-expect-message@1.1.00
# jest-expect-message
1
2
jest-expect-message extends Jest's expect function to support custom error messages, allowing developers to provide more descriptive failure messages when assertions fail. It provides seamless integration with existing Jest test suites and maintains full compatibility with all Jest matchers.
3
4
## Package Information
5
6
- **Package Name**: jest-expect-message
7
- **Package Type**: npm
8
- **Language**: JavaScript (with TypeScript support)
9
- **Installation**: `npm install --save-dev jest-expect-message`
10
11
## Core Imports
12
13
This package is a Jest setup extension and is imported through Jest configuration rather than direct import statements:
14
15
**Jest v24+ Configuration:**
16
```json
17
{
18
"jest": {
19
"setupFilesAfterEnv": ["jest-expect-message"]
20
}
21
}
22
```
23
24
**Jest v23- Configuration:**
25
```json
26
{
27
"jest": {
28
"setupTestFrameworkScriptFile": "jest-expect-message"
29
}
30
}
31
```
32
33
**Custom Setup File:**
34
```javascript
35
import 'jest-expect-message';
36
```
37
38
**TypeScript Configuration:**
39
```json
40
{
41
"files": ["node_modules/jest-expect-message/types/index.d.ts"]
42
}
43
```
44
45
## Basic Usage
46
47
```javascript
48
// Basic custom message
49
test('should add numbers correctly', () => {
50
expect(1 + 1, 'Addition should work correctly').toBe(2);
51
});
52
53
// Custom message with options
54
test('should validate user input', () => {
55
const user = { name: 'Alice', age: 25 };
56
expect(user.age, 'Age should be a valid number', {
57
showPrefix: false
58
}).toBeGreaterThan(18);
59
});
60
61
// Works with all Jest matchers
62
test('should handle arrays', () => {
63
const items = ['apple', 'banana'];
64
expect(items, 'Array should contain expected items').toContain('apple');
65
});
66
67
// Async expectations
68
test('should handle promises', async () => {
69
await expect(
70
Promise.resolve('success'),
71
'Promise should resolve with success message'
72
).resolves.toBe('success');
73
});
74
```
75
76
## Capabilities
77
78
### Enhanced Expect Function
79
80
The core functionality that enhances Jest's expect function to accept custom messages.
81
82
```javascript { .api }
83
/**
84
* Enhanced expect function with custom message support
85
* @param actual - The value to test (same as standard Jest expect)
86
* @param message - Optional custom error message to display on failure
87
* @param options - Optional configuration for message display
88
* @returns Jest matchers with custom message support
89
*/
90
expect(actual, message?, options?);
91
```
92
93
**Parameters:**
94
- `actual`: `any` - The value you would normally pass into an expect to assert against
95
- `message`: `string` (optional) - Custom message displayed when the expectation fails
96
- `options`: `MessageOptions` (optional) - Configuration object controlling message display
97
98
**Returns:** Standard Jest matchers (`JestMatchers<T>`) with custom message functionality
99
100
### Message Display Options
101
102
Configuration object for controlling how custom messages are displayed in test failures.
103
104
```javascript { .api }
105
interface MessageOptions {
106
/** Show "Custom message:" prefix before the message. Default: true */
107
showPrefix?: boolean;
108
/** Show the original matcher error message. Default: true */
109
showMatcherMessage?: boolean;
110
/** Show the stack trace in error output. Default: true */
111
showStack?: boolean;
112
}
113
```
114
115
**Properties:**
116
- `showPrefix`: `boolean` - Controls whether "Custom message:" prefix is shown (default: `true`)
117
- `showMatcherMessage`: `boolean` - Controls whether original Jest matcher message is shown (default: `true`)
118
- `showStack`: `boolean` - Controls whether stack trace is included in error output (default: `true`)
119
120
### Enhanced Expect.extend Method
121
122
The enhanced expect function preserves Jest's `extend` functionality for adding custom matchers.
123
124
```javascript { .api }
125
/**
126
* Extend Jest with custom matchers while preserving message functionality
127
* @param matchers - Object containing custom matcher functions
128
*/
129
expect.extend(matchers);
130
```
131
132
**Parameters:**
133
- `matchers`: `object` - Custom matchers to add to Jest's expect function
134
135
**Usage Example:**
136
```javascript
137
expect.extend({
138
toBeDivisibleBy(received, argument) {
139
const pass = received % argument === 0;
140
const message = pass
141
? () => `expected ${received} not to be divisible by ${argument}`
142
: () => `expected ${received} to be divisible by ${argument}`;
143
return { message, pass };
144
}
145
});
146
147
// Use custom matcher with custom message
148
test('custom matcher with message', () => {
149
expect(100, '100 should be divisible by 10').toBeDivisibleBy(10);
150
});
151
```
152
153
## Message Display Examples
154
155
### Default Message Display
156
157
```javascript
158
test('default message display', () => {
159
expect(1 + 1, 'Math should work correctly').toBe(3);
160
});
161
```
162
163
**Error Output:**
164
```
165
Custom message:
166
Math should work correctly
167
168
expect(received).toBe(expected) // Object.is equality
169
170
Expected: 3
171
Received: 2
172
```
173
174
### Hide Message Prefix
175
176
```javascript
177
test('hide prefix', () => {
178
expect(1 + 1, 'Math should work correctly', {
179
showPrefix: false
180
}).toBe(3);
181
});
182
```
183
184
**Error Output:**
185
```
186
Math should work correctly
187
188
expect(received).toBe(expected) // Object.is equality
189
190
Expected: 3
191
Received: 2
192
```
193
194
### Hide Original Matcher Message
195
196
```javascript
197
test('hide matcher message', () => {
198
expect(1 + 1, 'Math should work correctly', {
199
showMatcherMessage: false
200
}).toBe(3);
201
});
202
```
203
204
**Error Output:**
205
```
206
Custom message:
207
Math should work correctly
208
```
209
210
### Hide Stack Trace
211
212
```javascript
213
test('hide stack trace', () => {
214
expect(1 + 1, 'Math should work correctly', {
215
showStack: false
216
}).toBe(3);
217
});
218
```
219
220
**Error Output:**
221
```
222
Custom message:
223
Math should work correctly
224
225
expect(received).toBe(expected) // Object.is equality
226
227
Expected: 3
228
Received: 2
229
```
230
231
## TypeScript Support
232
233
The package includes comprehensive TypeScript definitions for type safety and IntelliSense support.
234
235
```typescript { .api }
236
declare namespace jest {
237
interface Expect {
238
<T = any>(
239
actual: T,
240
message?: string,
241
options?: {
242
showMatcherMessage?: boolean;
243
showPrefix?: boolean;
244
showStack?: boolean
245
}
246
): JestMatchers<T>;
247
}
248
}
249
```
250
251
**TypeScript Usage:**
252
```typescript
253
test('TypeScript example', () => {
254
const user: { name: string; age: number } = { name: 'Alice', age: 25 };
255
expect(user.age, 'Age should be valid').toBeGreaterThan(0);
256
});
257
```
258
259
## Compatibility and Integration
260
261
### Jest Matcher Compatibility
262
263
- **All Standard Matchers**: Works with `toBe`, `toEqual`, `toContain`, `toBeGreaterThan`, etc.
264
- **Negation Matchers**: Compatible with `.not` modifiers
265
- **Async Matchers**: Supports `.resolves` and `.rejects` for Promise testing
266
- **Custom Matchers**: Integrates seamlessly with `expect.extend()` custom matchers
267
- **Asymmetric Matchers**: Works with `expect.any()`, `expect.objectContaining()`, etc.
268
269
### ESLint Configuration
270
271
When using ESLint with jest rules, configure to allow 2 arguments for expect:
272
273
```json { .api }
274
{
275
"rules": {
276
"jest/valid-expect": [
277
"error",
278
{
279
"maxArgs": 2
280
}
281
]
282
}
283
}
284
```
285
286
### Setup Requirements
287
288
The package must be loaded before Jest runs tests. It modifies the global `expect` function to add message support while preserving all existing functionality.
289
290
**Important Notes:**
291
- No runtime dependencies
292
- Compatible with all Jest versions
293
- Preserves all existing Jest functionality
294
- Adds zero overhead when messages are not used
295
- Maintains full TypeScript type safety