Expose toMatchSnapshot in custom matchers
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.
expect.extend({
toMatchSnapshotTrimmed: function(received) {
return this.toMatchSnapshot(received.trim());
}
})
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
})
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 馃檪
Most helpful comment
The same outcome could currently be achieved using the following
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,
thiscontext will be lost