我在让 Chai 的 expect.to.throw
在我的 node.js 应用程序测试中工作时遇到问题。测试在抛出的错误上一直失败,但是如果我将测试用例包装在 try 中并捕获并断言捕获的错误,它就可以工作。
expect.to.throw
不能像我认为的那样工作吗?
it('should throw an error if you try to get an undefined property', function (done) {
var params = { a: 'test', b: 'test', c: 'test' };
var model = new TestModel(MOCK_REQUEST, params);
// neither of these work
expect(model.get('z')).to.throw('Property does not exist in model schema.');
expect(model.get('z')).to.throw(new Error('Property does not exist in model schema.'));
// this works
try {
model.get('z');
}
catch(err) {
expect(err).to.eql(new Error('Property does not exist in model schema.'));
}
done();
});
失败:
19 passing (25ms)
1 failing
1) Model Base should throw an error if you try to get an undefined property:
Error: Property does not exist in model schema.
最佳答案
你必须将一个函数传递给expect
。像这样:
expect(model.get.bind(model, 'z')).to.throw('Property does not exist in model schema.');
expect(model.get.bind(model, 'z')).to.throw(new Error('Property does not exist in model schema.'));
按照您的操作方式,您将调用 model.get('z')
的 result 传递给 expect
。但是要测试是否有东西被抛出,你必须将一个函数传递给 expect
,expect
会调用它自己。上面使用的 bind
方法创建了一个新函数,该函数在调用时将调用 model.get
并将 this
设置为 model< 的值
并且第一个参数设置为 'z'
。
bind
的一个很好的解释可以找到here .
关于javascript - Mocha/Chai expect.to.throw 没有捕捉到抛出的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21587122/