Jest: Expose `toMatchSnapshot` in custom matchers

Created on 7 May 2018  路  2Comments  路  Source: facebook/jest

馃殌 Feature Proposal

Expose toMatchSnapshot in custom matchers

Motivation

Snapshots can seem to vary in outcome across operating systems (see #6102 and #6113). To help prevent this we could normalise the differences in the snapshot.

Currently to normalise a snapshot you would have to do it in the data being snapshotted. By exposing toMatchSnapshot in custom matchers we can create reusable assertions .

This issue is related to #6115 and @rickhanlonii's comment on how to normalise whitespace in snapshots from within a custom matcher.

Example

expect.extend({
  toMatchSnapshotTrimmed: function(received) {
    return this.toMatchSnapshot(received.trim());
  }
})
Enhancement Help Wanted

Most helpful comment

The same outcome could currently be achieved using the following

// jest-setup.js

const snapshot = require('jest-snapshot');

function toMatchSnapshotTrimmed(received, customName){
  return snapshot.toMatchSnapshot.call(this, received.trim(), customName);
}

expect.extend({
  toMatchSnapshotTrimmed
})

Courtesy of https://github.com/jest-community/snapshot-diff/blob/2f987d90e4a5393192bd1c2c5cef358de9bd78d5/src/index.js#L94

By the way, you can't use arrow function for custom matcher, this context will be lost

All 2 comments

The same outcome could currently be achieved using the following

// jest-setup.js

const snapshot = require('jest-snapshot');

function toMatchSnapshotTrimmed(received, customName){
  return snapshot.toMatchSnapshot.call(this, received.trim(), customName);
}

expect.extend({
  toMatchSnapshotTrimmed
})

Courtesy of https://github.com/jest-community/snapshot-diff/blob/2f987d90e4a5393192bd1c2c5cef358de9bd78d5/src/index.js#L94

By the way, you can't use arrow function for custom matcher, this context will be lost

The idea to easily extend snapshot matchers is pretty neat. But, to do it this way, we would need to couple expect with jest-snapshot in some way (e.g. as a peer dependency) which we don't want to, because it ends up as a browser compatible package.

Since we can achieve the same pretty easily in user space, I think we're good leaving the scope of the expect package as is.

I'd be really happy to merge a PR explaining how to create a custom snapshot matcher in our Expect docs 馃檪

Was this page helpful?
0 / 5 - 0 ratings