1

我正在使用 chaijs 和 mochajs 进行单元测试。这是 chaijs 的文档。http://chaijs.com/api/bdd/

根据文档,它可以检查函数是否抛出异常。因此,使用此代码:

var expect = require("chai").expect;
describe("Testing", function(){
    var fn = function(){ throw new Error("hello"); };
    //map testing
    describe("map", function(){
        it("should return error",function(){
            expect(fn()).to.not.throw("hello");
        });
    });
});

测试应该说“通过”吧?它期待一个错误,而函数 fn 正在给出它。但我得到了这个:

  11 passing (37ms)
  1 failing

  1) Testing map should return error:
     Error: hello
      at fn (/vagrant/projects/AD/tests/shared/functionalTest.js:13:29)
      at Context.<anonymous> (/vagrant/projects/AD/tests/shared/functionalTest.js:17:11)
      at Test.Runnable.run (/vagrant/projects/AD/node_modules/mocha/lib/runnable.js:211:32)
      at Runner.runTest (/vagrant/projects/AD/node_modules/mocha/lib/runner.js:372:10)
      at /vagrant/projects/AD/node_modules/mocha/lib/runner.js:448:12
      at next (/vagrant/projects/AD/node_modules/mocha/lib/runner.js:297:14)
      at /vagrant/projects/AD/node_modules/mocha/lib/runner.js:307:7
      at next (/vagrant/projects/AD/node_modules/mocha/lib/runner.js:245:23)
      at Object._onImmediate (/vagrant/projects/AD/node_modules/mocha/lib/runner.js:274:5)
      at processImmediate [as _immediateCallback] (timers.js:330:15)

我很确定我在做一些愚蠢的事情,或者忘记了一些愚蠢的事情,我还没有注意到。

谁能看到我看不到的东西?或任何线索?谢谢。

顺便说一句,我正在使用 node.js v0.10.22。

4

2 回答 2

4

对于任何其他在测试对象方法抛出的错误时遇到问题的人:

考试

用匿名函数调用包装您的方法,它将起作用。

describe('myMath.sub()', function() {
   it('should handle bad data with exceptions', function(){
      var fn = function(){ myMath.sub('a',1); };
      expect(fn).to.throw("One or more values are not numbers");
   });
});

对象方法

exports.sub = function(a,b) {
   var val = a - b;
   if ( isNaN(val)) {
      var err = new Error("One or more values are not numbers");
      throw err;
      return 0;
   } else {
      return val;
   }
}
于 2014-03-12T08:59:54.613 回答
0

正如我所料,我遗漏了一些明显的东西!

我没有给出函数引用fn,而是给出了函数调用fn()

这是成功的代码

var expect = require("chai").expect;
describe("Testing", function(){
    var fn = function(){ throw new Error("hello"); };
    //map testing
    describe("map", function(){
        it("should return error",function(){
            expect(fn).to.throw("hello");
        });
    });
});
于 2014-01-17T17:46:01.773 回答