How can I print a pretty object diff in a Jest custom matcher?

Viewed 360

I'm writing a custom Jest matcher to compare 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)?

1 Answers

According 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 become:

const { diff } = require('jest-diff'); // already available if Jest is installed

// ...

message: () => "expect(received).toTorgle(expected):" + diff(received, expected),
Related