在chaijs做unit testing有关expect.throw的问题

我正在使用chaocha和mochajs进行unit testing。 这是chaijs的文件。 http://chaijs.com/api/bdd/

根据文档,它可以检查函数是否抛出exception。 所以,用这个代码:

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

testing应该说“通过”? 它期待一个错误,函数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。

对于其他人有麻烦testing从对象方法抛出的错误:

考试

用匿名函数调用你的方法,它将工作。

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

正如我所想,我错过了一些明显的东西!

而不是给函数引用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"); }); }); });