How to add custom message to Jest expect?

2020-05-24 19:49发布

Image following test case:

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

I would like to add auto-generated message for each email like Email 'f@f.com' should be valid so that it's easy to find failing test cases.

Something like:

// .map(email =>
expect(isValid(email), `Email ${email} should be valid`).toBe(true);

Is it possible in Jest ?

In Chai it was possible to do with second parameter like expect(value, 'custom fail message').to.be... and in Jasmine seems like it's done with .because clause. But cannot find solution in Jest.

7条回答
我想做一个坏孩纸
2楼-- · 2020-05-24 20:47

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);
查看更多
登录 后发表回答