【问题标题】:Fail a test with Chai.js使用 Chai.js 测试失败
【发布时间】:2016-02-18 18:29:06
【问题描述】:

在 JUnit 中,您可以通过以下方式使测试失败:

fail("Exception not thrown");

使用 Chai.js 实现相同目标的最佳方法是什么?

【问题讨论】:

    标签: javascript node.js chai


    【解决方案1】:

    试试吧

    expect.fail("custom error message");
    

    should.fail("custom error message");
    

    如 chai 文档中所述:https://www.chaijs.com/api/bdd/#method_fail

    【讨论】:

      【解决方案2】:

      我是这样做的

      const expect = require('chai').expect;
      const exists = true;
      expect(!exists).to.throw('Unknown request type');
      

      【讨论】:

        【解决方案3】:

        我还偶然发现这里没有直接的fail(msg)。 有一段时间,我和...一起工作过......

        assert.isOk(false, 'timeOut must throw')
        

        (在不应该到达的地方使用它,即在promise-testing中......)

        Chai 与标准 ES6 错误兼容,因此可以:

        throw new Error('timeOut must throw') 
        

        …或者,因为assert itself is essentially the same as assert.isOK…我最喜欢的是:

        assert(false,'timeOut must throw')
        

        ……嗯,几乎和assert.fail(…一样短。

        【讨论】:

          【解决方案4】:

          有很多方法可以伪造失败——比如@DmytroShevchenko 提到的assert.fail()——但通常可以避免这些拐杖并以更好的方式表达测试的意图,这将导致更多如果测试失败,则发出有意义的消息。

          例如,如果您希望抛出异常,为什么不直接说:

          expect( function () {
              // do stuff here which you expect to throw an exception
          } ).to.throw( Error );
          

          如您所见,在测试异常时,您必须将代码包装在匿名函数中。

          当然,您可以通过检查更具体的错误类型、预期的错误消息等来优化测试。有关更多信息,请参阅Chai docs 中的.throw

          【讨论】:

          • 我完全同意你所概述的是一种更好的方法。
          【解决方案5】:

          assert.fail()。你可以这样使用它:

          assert.fail(0, 1, 'Exception not thrown');
          

          【讨论】:

          • ...如果没有其他选择,你的答案是正确的,所以你也得到我的支持:)
          • @hashchange 有一个很好的例子,你可以使用它而不是“to.throw”,这就是你可能在对象构造函数中抛出错误的情况。
          猜你喜欢
          • 2014-01-28
          • 2022-07-25
          • 2017-08-04
          • 1970-01-01
          • 1970-01-01
          • 2019-11-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多