I'm writing a custom Jest matcher to pare objects in some arbitrary way:
expect.extend({
toTorgle(received, expected) {
...
return {
pass: false,
message: () => "expect(received).toTorgle(expected):" + ???
}
}
})
How can I print a nice object diff between the two objects, like the one that I get with (built-in matcher) expect(received).toEqual(expected)
?
I'm writing a custom Jest matcher to pare objects in some arbitrary way:
expect.extend({
toTorgle(received, expected) {
...
return {
pass: false,
message: () => "expect(received).toTorgle(expected):" + ???
}
}
})
How can I print a nice object diff between the two objects, like the one that I get with (built-in matcher) expect(received).toEqual(expected)
?
2 Answers
Reset to default 9According to Jest-Platform document, you can use jest-diff
to get a "pretty-printed" string illustrating the difference between the two arguments.
Your message
function will bee:
const { diff } = require('jest-diff'); // already available if Jest is installed
// ...
message: () => "expect(received).toTorgle(expected):" + diff(expected, received),
By default, the first argument to diff()
is labelled Expected
and the second is labelled Received
. This can be changed by supplying Options as a third argument. See the Options documentation.
Since vitest is getting traction over jest, it might be helpful sharing how to pretty print diff in vitest custom matcher.
In parison to jest, it's not necessary to employ jest-diff
package, because the custom matcher return type in vitest supports the actual and expected objects:
expect.extend({
toTorgle(received, expected) {
...
return {
pass: false,
message: () => 'expect(received).toTorgle(expected):',
actual: received,
expected,
}
}
});
Here's how the failing test output (with diff) will look like: