From dae7a129817072237387c377ad9e034bd78447a7 Mon Sep 17 00:00:00 2001 From: Matt Phillips Date: Mon, 13 Aug 2018 18:23:05 +0100 Subject: [PATCH 1/2] Add custom toMatchSnapshot matcher docs --- docs/ExpectAPI.md | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/docs/ExpectAPI.md b/docs/ExpectAPI.md index 5ce05ee5a0d7..c32d387644e6 100644 --- a/docs/ExpectAPI.md +++ b/docs/ExpectAPI.md @@ -156,6 +156,36 @@ This will print something like this: 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. +#### Custom snapshot matchers + +To use snapshot testing inside of your custom matcher you can import `jest-snapshot` and use it from within your matcher. + +Here's a simple snapshot matcher that trims a string to store for a given length, `.toMatchTrimmedSnapshot(length)`: + +```js +const {toMatchSnapshot} = require('jest-snapshot'); + +expect.extend({ + toMatchTrimmedSnapshot(received, length) { + return toMatchSnapshot.call( + this, + received.substring(0, length), + 'toMatchTrimmedSnapshot', + ); + }, +}); + +it('stores only 10 characters', () => { + expect('extra long string oh my gerd').toMatchTrimmedSnapshot(10); +}); + +/* +Stored snapshot will look like: + +exports[`stores only 10 characters: toMatchTrimmedSnapshot 1`] = `"extra long"`; +*/ +``` + ### `expect.anything()` `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: From 91c21d204cad2f9f89e207f0c73e0078218a2928 Mon Sep 17 00:00:00 2001 From: Matt Phillips Date: Mon, 13 Aug 2018 18:41:47 +0100 Subject: [PATCH 2/2] Add changelog entry --- CHANGELOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index ef7fadccec36..74f5f4b96db2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ ## master +### Chore & Maintenance + +- `[docs]` Add custom toMatchSnapshot matcher docs ([#6837](https://github.com/facebook/jest/pull/6837)) + ## 23.5.0 ### Features