为啥我的测试用例通过但断言实际上在 mocha 中失败

Posted

技术标签:

【中文标题】为啥我的测试用例通过但断言实际上在 mocha 中失败【英文标题】:Why is my test case passes but the assertion actually failed in mocha为什么我的测试用例通过但断言实际上在 mocha 中失败 【发布时间】:2021-12-18 08:10:33 【问题描述】:

我下面的测试用例通过但我的断言失败。为什么会过去?我已经有了异步,甚至没有调用 updateSpy,我的 Assertion failed 消息证实了这一点。我也尝试过用承诺完成。

it('should call the update  method once', async () => 
        const updateSpy = sinon.spy(() => 'Spy!');
    
        sinon.stub(service, 'db').resolves(
          collection(collectionName) 
            return 
              update: updateSpy,

                  ;
          ,
        );

       console.assert(updateSpy.called); // assertion failed but the test case was passed
  ); 

【问题讨论】:

因为你是console.assert。这只是将断言的结果记录到控制台。您需要使用一个会抛出错误的断言库,以便 Mocha 知道断言失败。 【参考方案1】:

来自ASSERTIONS 文档:

Mocha 允许您使用任何您想要的断言库。在上面的例子中,我们使用了 Node.js 的内置 assert 模块——但通常,如果它抛出一个 Error,它就会起作用!

但是如果断言为假,console.assert() 方法会向控制台写入错误消息。如果断言为真,则不会发生任何事情。如果断言为假,它将抛出Error

【讨论】:

以上是关于为啥我的测试用例通过但断言实际上在 mocha 中失败的主要内容,如果未能解决你的问题,请参考以下文章