首页 > 解决方案 > 使用 Chai+Mocha 测试失败的自定义特定错误消息?

问题描述

我正在为一个函数编写一个单元测试,并让它检查几十条测试数据。如果该函数不适用于其中一个测试用例,我希望它显示该函数失败的特定数据。

在我的例子中,我在后端有大约一百个函数我正在为其编写测试,并且我正在编写一些 Chai.jsassert()案例来检查许多测试数据。我不想让它跨数十条数据打印出相同功能的单个测试,因为我希望在整个后端运行测试时保持日志可读。

这是我目前编写测试的方式:

context('relative urls should be removed', function () {
  it('data should initially contain relative urls', async function () {
    assert(testHTML.every(containsRelativeURLs));
  });
  // (run testHTML through my function here)
  it('data should end with no relative urls', async function () {
    assert(!testHTML.every(containsRelativeURLs));
  })
});

如果我误解了编写单元测试的正确方法,请告诉我。如果有更清洁或更标准的方法来做到这一点,我很想知道。

标签: javascriptunit-testingtestingmocha.jschai

解决方案


assert可以带两个参数——第一个是你的断言,第二个是消息。您可以使用消息参数来记录信息。

describe('it passes all the tests /', ()=>{
    testData.forEach(testAsync =>
      it('should pass this test', async (done) => 
        const result = await testAsync
        assert(result === expectedResult, "bad ${result} returned by testAsync")
        done()
    )
})

推荐阅读