Jest snapshot testing utilities that enable capturing component output, API responses, or any serializable values as snapshots for regression testing and change detection
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
Specialized snapshot matchers for testing error messages and exception handling. These matchers capture error messages as snapshots, including support for error cause chains and inline snapshots.
Tests that a function throws an error whose message matches a stored snapshot in an external .snap file.
/**
* Tests that a function throws an error matching the most recent snapshot
* @param hint - Optional hint string to distinguish multiple error snapshots in one test
* @returns Matcher result indicating pass/fail status
*/
function toThrowErrorMatchingSnapshot(hint?: string): MatcherResult;Usage Examples:
// Note: toThrowErrorMatchingSnapshot is automatically available on expect() when using Jest
// No import from jest-snapshot is needed
// Basic error snapshot testing
test('throws validation error', () => {
expect(() => {
validateUser({ name: '', age: -1 });
}).toThrowErrorMatchingSnapshot();
});
// Multiple error snapshots with hints
test('throws different errors for different inputs', () => {
expect(() => {
processPayment({ amount: -100 });
}).toThrowErrorMatchingSnapshot('negative amount');
expect(() => {
processPayment({ amount: 0 });
}).toThrowErrorMatchingSnapshot('zero amount');
});
// Async function error testing
test('async operation throws error', async () => {
await expect(async () => {
await fetchUser('invalid-id');
}).rejects.toThrowErrorMatchingSnapshot();
});Tests that a function throws an error whose message matches an inline snapshot embedded directly in the source code.
/**
* Tests that a function throws an error matching an inline snapshot
* @param snapshot - Optional existing snapshot string (auto-generated if omitted)
* @returns Matcher result indicating pass/fail status
*/
function toThrowErrorMatchingInlineSnapshot(snapshot?: string): MatcherResult;Usage Examples:
// Note: toThrowErrorMatchingInlineSnapshot is automatically available on expect() when using Jest
// No import from jest-snapshot is needed
// Basic inline error snapshot
test('throws specific validation error', () => {
expect(() => {
validateEmail('invalid-email');
}).toThrowErrorMatchingInlineSnapshot(`"Invalid email format: must contain @ symbol"`);
});
// Complex error message with details
test('throws detailed parsing error', () => {
expect(() => {
parseJSON('{ invalid json }');
}).toThrowErrorMatchingInlineSnapshot(`
"JSON Parse Error: Unexpected token 'i' at position 2
Line 1, Column 3: { invalid json }
^"
`);
});
// Error with cause chain
test('throws error with cause chain', () => {
expect(() => {
processFile('nonexistent.txt');
}).toThrowErrorMatchingInlineSnapshot(`
"Failed to process file: nonexistent.txt
Cause: File not found: nonexistent.txt
Cause: ENOENT: no such file or directory"
`);
});The error snapshot matchers process error messages with special handling for:
Error Cause Chains: When an error has a cause property, the matcher traverses the entire chain and includes all error messages:
// Original error chain:
// Error: "Database connection failed"
// cause: Error: "Connection timeout"
// cause: "Network unreachable"
// Snapshot will contain:
// "Database connection failed
// Cause: Connection timeout
// Cause: Network unreachable"Native Error Detection: Uses types.isNativeError() and instanceof Error to properly identify error objects in the cause chain.
String Causes: Handles cases where error causes are plain strings rather than Error objects.
Function Validation: For non-promise matchers, validates that the received value is a function:
// Valid usage
expect(() => throwError()).toThrowErrorMatchingSnapshot();
// Invalid usage - will throw validation error
expect(someValue).toThrowErrorMatchingSnapshot();
// Error: "received value must be a function"Promise Handling: For promise-based testing, handles rejected promises directly:
// Promise rejection testing
await expect(async () => {
await asyncOperation();
}).rejects.toThrowErrorMatchingSnapshot();Error Absence: When the function doesn't throw an error:
expect(() => {
safeOperation();
}).toThrowErrorMatchingSnapshot();
// Error: "Received function did not throw"Error snapshot matchers integrate with Jest's standard error testing patterns:
// Combine with other error matchers
expect(() => {
validateInput(null);
}).toThrow()
.toThrowErrorMatchingSnapshot();
// Test error type and snapshot
expect(() => {
parseData('invalid');
}).toThrow(ValidationError)
.toThrowErrorMatchingSnapshot();Common error scenarios:
// Using with .not modifier (not supported)
expect(() => {
throwError();
}).not.toThrowErrorMatchingSnapshot();
// Error: "Snapshot matchers cannot be used with not"
// Invalid snapshot parameter
expect(() => {
throwError();
}).toThrowErrorMatchingInlineSnapshot(123);
// Error: "Inline snapshot must be a string"
// Missing snapshot state
expect(() => {
throwError();
}).toThrowErrorMatchingSnapshot();
// Error: "Snapshot state must be initialized"interface MatcherResult {
message(): string;
pass: boolean;
actual?: string;
expected?: string;
name: string;
}
type ErrorCause = Error | string | unknown;
interface ErrorWithCause extends Error {
cause?: ErrorCause;
}