javascript - 如何强制函数在使用 Mocha/Chai 调用时抛出异常

标签 javascript unit-testing mocha.js chai

我想测试函数 B 以使用 Mocha/Chai 捕获从函数 A 抛出的异常。

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);
  }
  ...
}

我想在测试B时强制A抛出异常。因此我可以确保函数 B 正确捕获 A 的异常。


搜索一些帖子后:

Test for expected failure in Mocha

Testing JS exceptions with Mocha/Chai

我没有找到正确答案。


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

最佳答案

这称为模拟。为了测试函数 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这简化了模拟和恢复

关于javascript - 如何强制函数在使用 Mocha/Chai 调用时抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31605988/

相关文章:

javascript - 检查表单是否填充了 jQuery

php - 用于 PHP 的服务器端 Web 浏览器?

javascript - FFT 与 offlineAudioContext

javascript - 将模拟 $state 注入(inject) Angular 单元测试

c++ - 如何在 Qt - Visual Studio 2013 项目中设置单元测试

javascript - Mocha 的 before() 函数的目的是什么?

javascript - 用 enzyme 模拟点击

javascript - Mocha : Can't seem to call module's methods that use jQuery from inside mocha tests

javascript - 使用 Google Analytics 的 Vuejs 事件跟踪

ios - 单元测试覆盖率%0