Add custom message to Jest expects
npx @tessl/cli install tessl/npm-jest-expect-message@1.1.0jest-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.
npm install --save-dev jest-expect-messageThis package is a Jest setup extension and is imported through Jest configuration rather than direct import statements:
Jest v24+ Configuration:
{
"jest": {
"setupFilesAfterEnv": ["jest-expect-message"]
}
}Jest v23- Configuration:
{
"jest": {
"setupTestFrameworkScriptFile": "jest-expect-message"
}
}Custom Setup File:
import 'jest-expect-message';TypeScript Configuration:
{
"files": ["node_modules/jest-expect-message/types/index.d.ts"]
}// Basic custom message
test('should add numbers correctly', () => {
expect(1 + 1, 'Addition should work correctly').toBe(2);
});
// Custom message with options
test('should validate user input', () => {
const user = { name: 'Alice', age: 25 };
expect(user.age, 'Age should be a valid number', {
showPrefix: false
}).toBeGreaterThan(18);
});
// Works with all Jest matchers
test('should handle arrays', () => {
const items = ['apple', 'banana'];
expect(items, 'Array should contain expected items').toContain('apple');
});
// Async expectations
test('should handle promises', async () => {
await expect(
Promise.resolve('success'),
'Promise should resolve with success message'
).resolves.toBe('success');
});The core functionality that enhances Jest's expect function to accept custom messages.
/**
* Enhanced expect function with custom message support
* @param actual - The value to test (same as standard Jest expect)
* @param message - Optional custom error message to display on failure
* @param options - Optional configuration for message display
* @returns Jest matchers with custom message support
*/
expect(actual, message?, options?);Parameters:
actual: any - The value you would normally pass into an expect to assert againstmessage: string (optional) - Custom message displayed when the expectation failsoptions: MessageOptions (optional) - Configuration object controlling message displayReturns: Standard Jest matchers (JestMatchers<T>) with custom message functionality
Configuration object for controlling how custom messages are displayed in test failures.
interface MessageOptions {
/** Show "Custom message:" prefix before the message. Default: true */
showPrefix?: boolean;
/** Show the original matcher error message. Default: true */
showMatcherMessage?: boolean;
/** Show the stack trace in error output. Default: true */
showStack?: boolean;
}Properties:
showPrefix: boolean - Controls whether "Custom message:" prefix is shown (default: true)showMatcherMessage: boolean - Controls whether original Jest matcher message is shown (default: true)showStack: boolean - Controls whether stack trace is included in error output (default: true)The enhanced expect function preserves Jest's extend functionality for adding custom matchers.
/**
* Extend Jest with custom matchers while preserving message functionality
* @param matchers - Object containing custom matcher functions
*/
expect.extend(matchers);Parameters:
matchers: object - Custom matchers to add to Jest's expect functionUsage Example:
expect.extend({
toBeDivisibleBy(received, argument) {
const pass = received % argument === 0;
const message = pass
? () => `expected ${received} not to be divisible by ${argument}`
: () => `expected ${received} to be divisible by ${argument}`;
return { message, pass };
}
});
// Use custom matcher with custom message
test('custom matcher with message', () => {
expect(100, '100 should be divisible by 10').toBeDivisibleBy(10);
});test('default message display', () => {
expect(1 + 1, 'Math should work correctly').toBe(3);
});Error Output:
Custom message:
Math should work correctly
expect(received).toBe(expected) // Object.is equality
Expected: 3
Received: 2test('hide prefix', () => {
expect(1 + 1, 'Math should work correctly', {
showPrefix: false
}).toBe(3);
});Error Output:
Math should work correctly
expect(received).toBe(expected) // Object.is equality
Expected: 3
Received: 2test('hide matcher message', () => {
expect(1 + 1, 'Math should work correctly', {
showMatcherMessage: false
}).toBe(3);
});Error Output:
Custom message:
Math should work correctlytest('hide stack trace', () => {
expect(1 + 1, 'Math should work correctly', {
showStack: false
}).toBe(3);
});Error Output:
Custom message:
Math should work correctly
expect(received).toBe(expected) // Object.is equality
Expected: 3
Received: 2The package includes comprehensive TypeScript definitions for type safety and IntelliSense support.
declare namespace jest {
interface Expect {
<T = any>(
actual: T,
message?: string,
options?: {
showMatcherMessage?: boolean;
showPrefix?: boolean;
showStack?: boolean
}
): JestMatchers<T>;
}
}TypeScript Usage:
test('TypeScript example', () => {
const user: { name: string; age: number } = { name: 'Alice', age: 25 };
expect(user.age, 'Age should be valid').toBeGreaterThan(0);
});toBe, toEqual, toContain, toBeGreaterThan, etc..not modifiers.resolves and .rejects for Promise testingexpect.extend() custom matchersexpect.any(), expect.objectContaining(), etc.When using ESLint with jest rules, configure to allow 2 arguments for expect:
{
"rules": {
"jest/valid-expect": [
"error",
{
"maxArgs": 2
}
]
}
}The package must be loaded before Jest runs tests. It modifies the global expect function to add message support while preserving all existing functionality.
Important Notes: