How to add custom message to Jest expect?

前端 未结 8 1194
鱼传尺愫
鱼传尺愫 2021-02-03 17:35

Image following test case:

it(\'valid emails checks\', () => {
  [\'abc@y.com\', \'a@b.nz\'/*, ...*/].map(mail => {
    expect(isValid(mail)).toBe(true);
          


        
8条回答
  •  醉梦人生
    2021-02-03 18:06

    Just had to deal with this myself I think I'll make a PR to it possibly: But this could work with whatever you'd like. Basically, you make a custom method that allows the curried function to have a custom message as a third parameter.

    It's important to remember that expect will set your first parameter (the one that goes into expect(akaThisThing) as the first parameter of your custom function.

    import diff from 'jest-diff'
    
    expect.extend({
    toBeMessage (received, expected, msg) {
      const pass = expected === received
      const message = pass
    ? () => `${this.utils.matcherHint('.not.toBe')}\n\n` +
            `Expected value to not be (using ===):\n` +
            `  ${this.utils.printExpected(expected)}\n` +
            `Received:\n` +
            `  ${this.utils.printReceived(received)}`
          : () => {
            const diffString = diff(expected, received, {
              expand: this.expand
            })
            return `${this.utils.matcherHint('.toBe')}\n\n` +
            `Expected value to be (using ===):\n` +
            `  ${this.utils.printExpected(expected)}\n` +
            `Received:\n` +
            `  ${this.utils.printReceived(received)}` +
            `${(diffString ? `\n\nDifference:\n\n${diffString}` : '')}\n` +
            `${(msg ? `Custom:\n  ${msg}` : '')}`
          }
    
        return { actual: received, message, pass }
      }
    })

    // usage:
    expect(myThing).toBeMessage(expectedArray, ' was not actually the expected array :(')

提交回复
热议问题