Skip to content

Commit 4ebc778

Browse files
mattphillipsthymikee
authored andcommitted
[docs]: Add custom toMatchSnapshot matcher docs (#6837)
## Summary Add docs for how to write custom matchers that use snapshot testing, following up from this: #6144 (comment)
1 parent b60f44a commit 4ebc778

2 files changed

Lines changed: 34 additions & 0 deletions

File tree

CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
## master
22

3+
### Chore & Maintenance
4+
5+
- `[docs]` Add custom toMatchSnapshot matcher docs ([#6837](https://github.com/facebook/jest/pull/6837))
6+
37
## 23.5.0
48

59
### Features

docs/ExpectAPI.md

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,36 @@ This will print something like this:
156156

157157
When an assertion fails, the error message should give as much signal as necessary to the user so they can resolve their issue quickly. You should craft a precise failure message to make sure users of your custom assertions have a good developer experience.
158158

159+
#### Custom snapshot matchers
160+
161+
To use snapshot testing inside of your custom matcher you can import `jest-snapshot` and use it from within your matcher.
162+
163+
Here's a simple snapshot matcher that trims a string to store for a given length, `.toMatchTrimmedSnapshot(length)`:
164+
165+
```js
166+
const {toMatchSnapshot} = require('jest-snapshot');
167+
168+
expect.extend({
169+
toMatchTrimmedSnapshot(received, length) {
170+
return toMatchSnapshot.call(
171+
this,
172+
received.substring(0, length),
173+
'toMatchTrimmedSnapshot',
174+
);
175+
},
176+
});
177+
178+
it('stores only 10 characters', () => {
179+
expect('extra long string oh my gerd').toMatchTrimmedSnapshot(10);
180+
});
181+
182+
/*
183+
Stored snapshot will look like:
184+
185+
exports[`stores only 10 characters: toMatchTrimmedSnapshot 1`] = `"extra long"`;
186+
*/
187+
```
188+
159189
### `expect.anything()`
160190

161191
`expect.anything()` matches anything but `null` or `undefined`. You can use it inside `toEqual` or `toBeCalledWith` instead of a literal value. For example, if you want to check that a mock function is called with a non-null argument:

0 commit comments

Comments
 (0)