How to add custom message to Jest expect?

前端 未结 8 1206
鱼传尺愫
鱼传尺愫 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
    

提交回复
热议问题