【问题标题】:Mocha/Chai: testing thrown Errors with error messageMocha/Chai:使用错误消息测试抛出的错误
【发布时间】:2020-07-03 14:03:54
【问题描述】:

这是this question的后续问题:

我不仅要测试函数是否抛出错误,还要测试抛出的错误是否具有相同的错误消息。 所以我尝试了:

expect(Person.getPerson.bind(Person, id)).to.throw(new Error(`Person ${id} not found`));

在 getPerson 函数内部会抛出一个错误,如下所示:

if (!isPersonExistent(id)) {
   throw new Error(`Person ${id} not found`);
}

给定的消息如下所示:

AssertionError: expected [Function: bound getPerson] to throw 'Error: Person 1 not found' but 'Error: Person 1 not found' was thrown

我想这与两个错误对象是两个不同的对象有关。但是我如何也测试他们是否有相同的错误信息。最好一步完成。

【问题讨论】:

    标签: typescript testing mocha.js chai


    【解决方案1】:

    您的断言失败是正确的,因为 Chai .throw 正在通过严格相等来比较错误对象。来自the spec

    当提供了一个参数并且它是一个错误实例时,.throw 调用目标函数并断言抛出一个严格 (===) 等于该错误实例的错误。

    相同的规范解释:

    当提供两个参数时,第一个是错误实例或构造函数,第二个是字符串或正则表达式,.throw 调用该函数并断言抛出一个满足上述两个条件的错误。

    在哪里

    .throw 调用目标函数并断言抛出错误并带有包含该字符串的消息。

    所以测试所需行为的方法是使用两个这样的参数:

    expect(Person.getPerson.bind(Person, id)).to.throw(Error, `Person ${id} not found`);
    

    【讨论】:

      【解决方案2】:

      试试这个:

      try {
        Person.getPerson(id);
      } catch (error) {
        expect(error.message).to.be('Error: Person 1 not found');
        return;
      }
      expect.fail('Should have thrown');
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-11-14
        • 1970-01-01
        • 1970-01-01
        • 2018-10-02
        • 1970-01-01
        • 2017-10-23
        • 1970-01-01
        • 2013-02-04
        相关资源
        最近更新 更多