如何向Jest添加自定义消息?

时间:2017-07-27 10:26:14

标签: javascript unit-testing jestjs

以下测试用例的图片:

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

我想为Email 'f@f.com' should be valid等每封电子邮件添加自动生成的消息,以便轻松找到失败的测试用例。

类似的东西:

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

是否可以在 Jest

在Chai中可以使用第二个参数,例如expect(value, 'custom fail message').to.be...,而在Jasmine中,似乎已经完成了.because子句。但是在Jest中找不到解决方案。

11 个答案:

答案 0 :(得分:10)

我认为不可能提供这样的信息。但您可以定义自己的matcher

例如,您可以创建toBeValid(validator)匹配器:

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
      };
    }
  }
});

然后你就这样使用它:

expect(mail).toBeValid(isValid);

注意:toBeValid会为两种情况(成功和失败)返回一条消息,因为它允许您使用.not。根据您是否希望它通过验证,测试将失败并显示相应的消息。

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

答案 1 :(得分:4)

您可以使用try-catch:

try {
    expect(methodThatReturnsBoolean(inputValue)).toBeTruthy();
}
catch (e) {
    throw new Error(`Should return true on input ${JSON.stringify(inputValue)}`, e);
}

答案 2 :(得分:4)

尽管这不是通用解决方案,但对于希望自定义异常消息来区分循环中项目的常见情况,您可以改为使用Jest的test.each

例如,您的示例代码:

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

可以代替

test.each(
    ['abc@y.com', 'a@b.nz'/*, ...*/],
    'checks that email %s is valid',
    mail => {
        expect(isValid(mail)).toBe(true);
    }
);

答案 3 :(得分:2)

您尝试以下一种方法: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);
});

答案 4 :(得分:1)

我必须自己处理这个问题,我想我可能会对它做一个公关:但这可能适用于你想要的任何东西。基本上,您创建一个自定义方法,允许curried函数将自定义消息作为第三个参数。

重要的是要记住,expect会设置你的第一个参数(expect(akaThisThing)作为自定义函数的第一个参数。

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 :(')

答案 5 :(得分:0)

您可以使用:(您可以在测试中定义它)

      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+')',
          };
    }
},  });

并像这样使用它

     let z = 'TheMassageYouWantWhenErrror';
    expect(first.name).ToBeMatch(second.name,z);

答案 6 :(得分:0)

您可以重写expect断言以使用toThrow()not.toThrow()。然后使用您的自定义文本引发错误。 jest将在输出中包含自定义文本。

// 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()

答案 7 :(得分:0)

添加自定义错误消息的另一种方法是使用fail()方法:

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()
    }
  })
})

答案 8 :(得分:0)

我最终只是用逻辑测试条件,然后将 fail() 与字符串模板一起使用。

it('key should not be found in object', () => {
    for (const key in object) {
      if (Object.prototype.hasOwnProperty.call(object, key)) {
        const element = object[key];
        if (element["someKeyName"] === false) {
          if (someCheckerSet.includes(key) === false) {
            fail(`${key} was not found in someCheckerSet.`)
          }
        }

答案 9 :(得分:0)

扩展@Zargold's answer

<块引用>

有关更多选项,例如下面的 comment,请参阅 MatcherHintOptions doc

// custom matcher - omit expected
expect.extend({
  toBeAccessible(received) {
    if (pass) return { pass };
    return {
      pass,
      message: () =>
        `${this.utils.matcherHint('toBeAccessible', 'received', '', {
          comment: 'visible to screen readers',
        })}\n
Expected: ${this.utils.printExpected(true)}
Received: ${this.utils.printReceived(false)}`,
    };
  }

enter image description here

// custom matcher - include expected
expect.extend({
  toBeAccessible(received) {
    if (pass) return { pass };
    return {
      pass,
      message: () =>
        `${this.utils.matcherHint('toBeAccessible', 'received', 'expected', { // <--
          comment: 'visible to screen readers',
        })}\n
Expected: ${this.utils.printExpected(true)}
Received: ${this.utils.printReceived(false)}`,
    };
  }

enter image description here

答案 10 :(得分:0)

2021 答案

我在为 Mintbean 编写的一些代码中做到了这一点,将我的 it 块放在 forEach 中。

通过这样做,我能够非常接近您所描述的内容。

优点:

  • 出色的“本机”错误报告
  • 将断言视为自己的测试
  • 无需插件。

以下是使用我的方法时您的代码的样子:


// you can't nest "it" blocks within each other,
// so this needs to be inside a describe block. 
describe('valid emails checks', () => {
  ['abc@y.com', 'a@b.nz'/*, ...*/].forEach(mail => {
    // here is where the magic happens
    it(`accepts ${mail} as a valid email`, () => {
      expect(isValid(mail)).toBe(true);
    })
  });
});

错误会像这样显示。

注意这些有多好!

 FAIL  path/to/your.test.js
  ● valid emails checks › accepts abc@y.com as a valid email

    expect(received).toBe(expected)

    Expected: "abc@y.com"
    Received: "xyz@y.com"

      19 |    // here is where the magic happens
      20 |    it(`accepts ${mail} as a valid email`, () => {
    > 21 |      expect(isValid(mail)).toBe(true);
                                       ^
      22 |    })