How to add custom message to Jest expect?

前端 未结 8 1202
鱼传尺愫
鱼传尺愫 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 17:47

    I don't think it's possible to provide a message like that. But you could define your own matcher.

    For example you could create a toBeValid(validator) matcher:

    expect.extend({
      toBeValid(received, validator) {
        if (validator(received)) {
          return {
            message: () => `Email ${received} should NOT be valid`,
            pass: true
          };
        } else {
          return {
            message: () => `Email ${received} should be valid`,
            pass: false
          };
        }
      }
    });
    

    And then you use it like this:

    expect(mail).toBeValid(isValid);
    

    Note: toBeValid returns a message for both cases (success and failure), because it allows you to use .not. The test will fail with the corresponding message depending on whether you want it to pass the validation.

    expect(mail).toBeValid(isValid);
    // pass === true: Test passes
    // pass === false: Failure: Email ... should be valid
    
    expect(mail).not.toBeValid(isValid);
    // pass === true: Failure: Email ... should NOT be valid
    // pass === false: Test passes
    
    0 讨论(0)
  • 2021-02-03 17:54

    You try this one: https://github.com/mattphillips/jest-expect-message

    test('returns 2 when adding 1 and 1', () => {
      expect(1 + 1, 'Woah this should be 2!').toBe(3);
    });
    
    0 讨论(0)
  • 2021-02-03 17:54

    You can rewrite the expect assertion to use toThrow() or not.toThrow(). Then throw an Error with your custom text. jest will include the custom text in the output.

    // Closure which returns function which may throw
    function isValid (email) {
      return () => {
         // replace with a real test!
         if (email !== 'some@example.com') {
           throw new Error(`Email ${email} not valid`)
         }
      }
    }
    
    expect(isValid(email)).not.toThrow()
    
    
    0 讨论(0)
  • 2021-02-03 17:56

    you can use this: (you can define it inside the test)

          expect.extend({
    ToBeMatch(expect, toBe, Msg) {  //Msg is the message you pass as parameter
        const pass = expect === toBe;
        if(pass){//pass = true its ok
            return {
                pass: pass,
                message: () => 'No ERRORS ',
              };
        }else{//not pass
            return {
                pass: pass,
                message: () => 'Error in Field   '+Msg + '  expect  ' +  '  ('+expect+') ' + 'recived '+'('+toBe+')',
              };
        }
    },  });
    

    and use it like this

         let z = 'TheMassageYouWantWhenErrror';
        expect(first.name).ToBeMatch(second.name,z);
    
    0 讨论(0)
  • 2021-02-03 18:05

    Another way to add a custom error message is by using the fail() method:

    it('valid emails checks', (done) => {
      ['abc@y.com', 'a@b.nz'/*, ...*/].map(mail => {
        if (!isValid(mail)) {
          done.fail(`Email '${mail}' should be valid`)
        } else {
          done()
        }
      })
    })
    
    0 讨论(0)
  • 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 :(')

    0 讨论(0)
提交回复
热议问题