我用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。
发布于 2014-01-17 17:46:01
就像我想的,我错过了一些显而易见的东西!
我不是给函数引用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");
        });
    });
});https://stackoverflow.com/questions/21191826
复制相似问题