or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

cleanup.mderror-snapshots.mdindex.mdpath-resolution.mdserialization.mdsnapshot-matchers.mdstate-management.md
tile.json

error-snapshots.mddocs/

0

# Error Snapshot Testing

1

2

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.

3

4

## Capabilities

5

6

### toThrowErrorMatchingSnapshot

7

8

Tests that a function throws an error whose message matches a stored snapshot in an external `.snap` file.

9

10

```typescript { .api }

11

/**

12

* Tests that a function throws an error matching the most recent snapshot

13

* @param hint - Optional hint string to distinguish multiple error snapshots in one test

14

* @returns Matcher result indicating pass/fail status

15

*/

16

function toThrowErrorMatchingSnapshot(hint?: string): MatcherResult;

17

```

18

19

**Usage Examples:**

20

21

```typescript

22

// Note: toThrowErrorMatchingSnapshot is automatically available on expect() when using Jest

23

// No import from jest-snapshot is needed

24

25

// Basic error snapshot testing

26

test('throws validation error', () => {

27

expect(() => {

28

validateUser({ name: '', age: -1 });

29

}).toThrowErrorMatchingSnapshot();

30

});

31

32

// Multiple error snapshots with hints

33

test('throws different errors for different inputs', () => {

34

expect(() => {

35

processPayment({ amount: -100 });

36

}).toThrowErrorMatchingSnapshot('negative amount');

37

38

expect(() => {

39

processPayment({ amount: 0 });

40

}).toThrowErrorMatchingSnapshot('zero amount');

41

});

42

43

// Async function error testing

44

test('async operation throws error', async () => {

45

await expect(async () => {

46

await fetchUser('invalid-id');

47

}).rejects.toThrowErrorMatchingSnapshot();

48

});

49

```

50

51

### toThrowErrorMatchingInlineSnapshot

52

53

Tests that a function throws an error whose message matches an inline snapshot embedded directly in the source code.

54

55

```typescript { .api }

56

/**

57

* Tests that a function throws an error matching an inline snapshot

58

* @param snapshot - Optional existing snapshot string (auto-generated if omitted)

59

* @returns Matcher result indicating pass/fail status

60

*/

61

function toThrowErrorMatchingInlineSnapshot(snapshot?: string): MatcherResult;

62

```

63

64

**Usage Examples:**

65

66

```typescript

67

// Note: toThrowErrorMatchingInlineSnapshot is automatically available on expect() when using Jest

68

// No import from jest-snapshot is needed

69

70

// Basic inline error snapshot

71

test('throws specific validation error', () => {

72

expect(() => {

73

validateEmail('invalid-email');

74

}).toThrowErrorMatchingInlineSnapshot(`"Invalid email format: must contain @ symbol"`);

75

});

76

77

// Complex error message with details

78

test('throws detailed parsing error', () => {

79

expect(() => {

80

parseJSON('{ invalid json }');

81

}).toThrowErrorMatchingInlineSnapshot(`

82

"JSON Parse Error: Unexpected token 'i' at position 2

83

Line 1, Column 3: { invalid json }

84

^"

85

`);

86

});

87

88

// Error with cause chain

89

test('throws error with cause chain', () => {

90

expect(() => {

91

processFile('nonexistent.txt');

92

}).toThrowErrorMatchingInlineSnapshot(`

93

"Failed to process file: nonexistent.txt

94

Cause: File not found: nonexistent.txt

95

Cause: ENOENT: no such file or directory"

96

`);

97

});

98

```

99

100

### Error Message Processing

101

102

The error snapshot matchers process error messages with special handling for:

103

104

**Error Cause Chains**: When an error has a `cause` property, the matcher traverses the entire chain and includes all error messages:

105

106

```typescript

107

// Original error chain:

108

// Error: "Database connection failed"

109

// cause: Error: "Connection timeout"

110

// cause: "Network unreachable"

111

112

// Snapshot will contain:

113

// "Database connection failed

114

// Cause: Connection timeout

115

// Cause: Network unreachable"

116

```

117

118

**Native Error Detection**: Uses `types.isNativeError()` and `instanceof Error` to properly identify error objects in the cause chain.

119

120

**String Causes**: Handles cases where error causes are plain strings rather than Error objects.

121

122

### Matcher Behavior

123

124

**Function Validation**: For non-promise matchers, validates that the received value is a function:

125

126

```typescript

127

// Valid usage

128

expect(() => throwError()).toThrowErrorMatchingSnapshot();

129

130

// Invalid usage - will throw validation error

131

expect(someValue).toThrowErrorMatchingSnapshot();

132

// Error: "received value must be a function"

133

```

134

135

**Promise Handling**: For promise-based testing, handles rejected promises directly:

136

137

```typescript

138

// Promise rejection testing

139

await expect(async () => {

140

await asyncOperation();

141

}).rejects.toThrowErrorMatchingSnapshot();

142

```

143

144

**Error Absence**: When the function doesn't throw an error:

145

146

```typescript

147

expect(() => {

148

safeOperation();

149

}).toThrowErrorMatchingSnapshot();

150

// Error: "Received function did not throw"

151

```

152

153

### Integration with Standard Matchers

154

155

Error snapshot matchers integrate with Jest's standard error testing patterns:

156

157

```typescript

158

// Combine with other error matchers

159

expect(() => {

160

validateInput(null);

161

}).toThrow()

162

.toThrowErrorMatchingSnapshot();

163

164

// Test error type and snapshot

165

expect(() => {

166

parseData('invalid');

167

}).toThrow(ValidationError)

168

.toThrowErrorMatchingSnapshot();

169

```

170

171

### Error Handling

172

173

Common error scenarios:

174

175

```typescript

176

// Using with .not modifier (not supported)

177

expect(() => {

178

throwError();

179

}).not.toThrowErrorMatchingSnapshot();

180

// Error: "Snapshot matchers cannot be used with not"

181

182

// Invalid snapshot parameter

183

expect(() => {

184

throwError();

185

}).toThrowErrorMatchingInlineSnapshot(123);

186

// Error: "Inline snapshot must be a string"

187

188

// Missing snapshot state

189

expect(() => {

190

throwError();

191

}).toThrowErrorMatchingSnapshot();

192

// Error: "Snapshot state must be initialized"

193

```

194

195

## Types

196

197

```typescript { .api }

198

interface MatcherResult {

199

message(): string;

200

pass: boolean;

201

actual?: string;

202

expected?: string;

203

name: string;

204

}

205

206

type ErrorCause = Error | string | unknown;

207

208

interface ErrorWithCause extends Error {

209

cause?: ErrorCause;

210

}

211

```