我正在尝试测试我的构造函数将使用Teaspoon gem for Rails抛出错误,ChaiJS作为我的断言库。
当我运行以下测试时:
it('does not create the seat if x < 0', function() {
var badConstructor = function() {
return new Seat({ radius: 10, x: -0.1, y: 0.2, seat_number: 20, table_number: 30});
};
expect(badConstructor).to.throw(Error, 'Invalid location');
});
我得到了这个输出:
故障:
1) Seat does not create the seat if x < 0
Failure/Error: undefined is not a constructor (evaluating 'expect(badConstructor).to.throw(Error(), 'Invalid location')')
构造函数抛出错误,但我认为我没有正确编写测试。
当我尝试运行expect(badConstructor())
时,我得到了输出:
Failures:
1) Seat does not create the seat if x < 0
Failure/Error: Invalid location
答案 0 :(得分:28)
有同样的问题。使用函数包装构造函数:
var fcn = function(){new badConstructor()};
expect(fcn).to.throw(Error, 'Invalid location');
答案 1 :(得分:3)
要测试构造函数内部的抛出消息错误,可以使用mocha和chai编写此测试(使用ES6语法):
innerExecutor()
请参阅此笔,以查看zJppaj上的Diego A. ZapataHäntsch(@diegoazh)上的代码CodePen的检查实时工作。
答案 2 :(得分:0)
完整示例:
function fn(arg) {
if (typeof arg !== 'string')
throw TypeError('Must be an string')
return { arg: arg }
}
it('#fn', function () {
expect(fn).to.throw(TypeError)
expect(fn.bind(2)).to.throw(TypeError)
expect(fn('str')).to.be.equal('str')
})