【问题标题】:How to force a function to throw exception when it invoked with Mocha/Chai使用 Mocha/Chai 调用时如何强制函数抛出异常
【发布时间】:2015-07-24 08:44:50
【问题描述】:

我想测试function B 以捕获从function AMocha/Chai 引发的异常。

function A() {
  // 1. the third party API is called here
  // some exception may be thrown from it
  ...
  // 2. some exception could be thrown here
  // caused by the logic in this function
}

function B() {
  // To catch exception thrown by A()
  try {
     A();
  } catch(err) {
     console.error(err);
  }
  ...
}

我想强制A 抛出异常,同时对B 进行测试。所以我可以确保函数B 正确捕获来自A 的异常。


搜索了一些帖子后:

Test for expected failure in Mocha

Testing JS exceptions with Mocha/Chai

我没有找到正确的答案。


我的问题合理吗?如果是,如何使用Mocha/Chai 进行该测试?

【问题讨论】:

  • 你不能只在你的 A 函数中 throw 'error'; 吗?

标签: javascript unit-testing mocha.js chai


【解决方案1】:

这称为模拟。为了测试函数B,您应该模拟函数A 以正确运行。因此,在测试之前,您定义 A 之类的 A = function(){ throw new Error('for test');} 调用并验证调用时 B 的行为是否相应。

describe('alphabet', function(){
    describe('A', function(){
         var _A;
         beforeEach(function(){
             var _A = A; //save original function
             A = function () {
                  throw new Error('for test');
             }
         });
         it('should catch exceptions in third party', function(){
             B();
             expect(whatever).to.be.true;
         });
         afterEach(function(){
             A = _A;//restore original function for other tests
         });
    }
})

由于您已经在使用 Mocha 和 Chai,您可能有兴趣研究 Sinon。它极大地扩展了 Mocha 的功能。在这种情况下,您将使用stubs 来简化模拟和恢复

【讨论】:

    猜你喜欢
    • 2020-08-29
    • 2015-06-02
    • 1970-01-01
    • 2017-01-19
    • 2016-12-15
    • 1970-01-01
    • 1970-01-01
    • 2013-09-26
    • 2016-03-20
    相关资源
    最近更新 更多