摩卡与期望是不工作的testing错误

在下面的脚本中只有一个testing通过。 testing错误(throw Error())失败,消息1)testing应该抛出错误:

var expect = require('chai').expect; describe("a test", function() { var fn; before(function() { fn = function(arg){ if(arg == 'error'){ throw new Error(); }else{ return 'hi'; } } }); it("should throw error", function() { expect(fn('error')).to.throw(Error); }); it("should return hi", function() { expect(fn('hi')).to.equal('hi'); }); }); 

如何改变期望来testing错误?

expect()需要一个函数来调用,而不是函数的结果。

将您的代码更改为:

 expect(function(){ fn("error"); }).to.throw(Error); 

如果你使用错误优先callback的方式来实现它,它看起来更像这样:

 var expect = require('chai').expect; describe("a test", function() { var fn; before(function() { fn = function(err, callback){ if(err) throw new Error('failure'); return callback(); } }); it("should throw error", function() { expect(fn('error')).to.throw(Error); }); it("should return hi", function() { var callback = function() { return 'hi' }; expect(fn(null, callback).to.equal('hi'); }); });