最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I print a pretty object diff in a Jest custom matcher? - Stack Overflow

programmeradmin0浏览0评论

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)?

Share Improve this question asked Jan 4, 2022 at 20:48 SasgorillaSasgorilla 3,1308 gold badges44 silver badges77 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 9

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

发布评论

评论列表(0)

  1. 暂无评论