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

snapshot-matchers.mddocs/

0

# Snapshot Matchers

1

2

Jest matchers that compare received values against stored snapshots, supporting both external `.snap` files and inline snapshots embedded directly in source code. These matchers are implemented by jest-snapshot and automatically added to Jest's `expect()` function.

3

4

## Capabilities

5

6

### toMatchSnapshot

7

8

Compares a received value against a stored snapshot in an external `.snap` file. Supports optional property matchers for partial object comparison and hint strings for multiple snapshots in a single test.

9

10

```typescript { .api }

11

/**

12

* Ensures that a value matches the most recent snapshot

13

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

14

* @returns Matcher result indicating pass/fail status

15

*/

16

function toMatchSnapshot(hint?: string): MatcherResult;

17

18

/**

19

* Ensures that a value matches the most recent snapshot with property matchers

20

* @param propertyMatchers - Partial object with expected property values or matchers

21

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

22

* @returns Matcher result indicating pass/fail status

23

*/

24

function toMatchSnapshot<U extends Record<keyof T, unknown>>(

25

propertyMatchers: Partial<U>,

26

hint?: string

27

): MatcherResult;

28

```

29

30

**Usage Examples:**

31

32

```typescript

33

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

34

// No import from jest-snapshot is needed

35

36

// Basic snapshot matching

37

test('renders component correctly', () => {

38

const component = render(<MyComponent />);

39

expect(component).toMatchSnapshot();

40

});

41

42

// Multiple snapshots with hints

43

test('renders in different states', () => {

44

expect(render(<Button disabled />)).toMatchSnapshot('disabled state');

45

expect(render(<Button loading />)).toMatchSnapshot('loading state');

46

});

47

48

// Property matching for dynamic values

49

test('user with partial matching', () => {

50

const user = {

51

id: 123,

52

name: 'John',

53

timestamp: Date.now(),

54

settings: { theme: 'dark' }

55

};

56

57

expect(user).toMatchSnapshot({

58

id: expect.any(Number),

59

name: 'John',

60

settings: { theme: 'dark' }

61

// timestamp excluded from snapshot

62

});

63

});

64

```

65

66

### toMatchInlineSnapshot

67

68

Compares a received value against an inline snapshot that is written directly into the source code. The snapshot value is embedded as a string argument to the matcher function.

69

70

```typescript { .api }

71

/**

72

* Ensures that a value matches an inline snapshot in source code

73

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

74

* @returns Matcher result indicating pass/fail status

75

*/

76

function toMatchInlineSnapshot(snapshot?: string): MatcherResult;

77

78

/**

79

* Ensures that a value matches an inline snapshot with property matchers

80

* @param propertyMatchers - Partial object with expected property values or matchers

81

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

82

* @returns Matcher result indicating pass/fail status

83

*/

84

function toMatchInlineSnapshot<U extends Record<keyof T, unknown>>(

85

propertyMatchers: Partial<U>,

86

snapshot?: string

87

): MatcherResult;

88

```

89

90

**Usage Examples:**

91

92

```typescript

93

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

94

// No import from jest-snapshot is needed

95

96

// Basic inline snapshot (Jest will auto-generate the snapshot string)

97

test('calculates result', () => {

98

const result = calculate(2, 3);

99

expect(result).toMatchInlineSnapshot(`5`);

100

});

101

102

// Object inline snapshot

103

test('creates user object', () => {

104

const user = createUser('John', 25);

105

expect(user).toMatchInlineSnapshot(`

106

Object {

107

"age": 25,

108

"id": Any<Number>,

109

"name": "John",

110

}

111

`);

112

});

113

114

// Property matching with inline snapshot

115

test('API response with dynamic fields', () => {

116

const response = await fetchUser(123);

117

expect(response).toMatchInlineSnapshot(

118

{

119

timestamp: expect.any(Number),

120

requestId: expect.any(String)

121

},

122

`

123

Object {

124

"data": Object {

125

"name": "John",

126

"email": "john@example.com"

127

},

128

"requestId": Any<String>,

129

"status": "success",

130

"timestamp": Any<Number>

131

}

132

`

133

);

134

});

135

136

// Multi-line string snapshot

137

test('generates SQL query', () => {

138

const query = buildQuery({ table: 'users', where: { active: true } });

139

expect(query).toMatchInlineSnapshot(`

140

"SELECT * FROM users

141

WHERE active = true"

142

`);

143

});

144

```

145

146

### Matcher Behavior

147

148

**First Run**: When a test runs for the first time:

149

- **toMatchSnapshot**: Creates a new `.snap` file with the serialized value

150

- **toMatchInlineSnapshot**: Inserts the serialized value directly into the source code

151

152

**Subsequent Runs**: On later test runs:

153

- Compares the received value against the stored snapshot

154

- Fails if values don't match (unless in update mode)

155

156

**Update Mode**: When running with `--updateSnapshot`:

157

- Updates existing snapshots with new received values

158

- Useful when intentional changes are made to components or data structures

159

160

**Property Matchers**: Allow partial snapshot matching:

161

- Use `expect.any(Type)` for type-only matching

162

- Use specific values for exact matches

163

- Omit properties to exclude them from the snapshot entirely

164

165

### Error Handling

166

167

Common error scenarios and their meanings:

168

169

```typescript

170

// Missing snapshot state

171

expect(value).toMatchSnapshot();

172

// Error: "Snapshot state must be initialized"

173

174

// Invalid property matchers

175

expect(value).toMatchSnapshot(123);

176

// Error: "Expected properties must be an object"

177

178

// Wrong property matcher type

179

expect(value).toMatchSnapshot({ id: 123 }, 456);

180

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

181

182

// Using with .not modifier

183

expect(value).not.toMatchSnapshot();

184

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

185

```

186

187

## Types

188

189

```typescript { .api }

190

interface MatcherResult {

191

message(): string;

192

pass: boolean;

193

actual?: unknown;

194

expected?: unknown;

195

name?: string;

196

}

197

198

type MatcherContext = {

199

isNot: boolean;

200

promise: string;

201

currentTestName?: string;

202

currentConcurrentTestName?: () => string;

203

equals: (a: unknown, b: unknown, customTesters?: Array<Tester>) => boolean;

204

utils: MatcherUtils;

205

error?: Error;

206

dontThrow?: () => void;

207

};

208

```