Mocha/Chai expect.to.throw 没有捕捉到抛出的错误 [英] Mocha / Chai expect.to.throw not catching thrown errors
问题描述
我在让 Chai 的 expect.to.throw
测试我的 node.js 应用程序时遇到问题.测试在抛出的错误上一直失败,但是如果我将测试用例包装在 try 和 catch 中,并对捕获的错误进行断言,它就可以工作.
I'm having issues getting Chai's expect.to.throw
to work in a test for my node.js app. The test keeps failing on the thrown error, but If I wrap the test case in try and catch and assert on the caught error, it works.
expect.to.throw
是不是像我认为的那样不工作?
Does expect.to.throw
not work like I think it should or something?
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
.像这样:
You have to pass a function to expect
. Like this:
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<的值/code> 并且第一个参数设置为
'z'
.
The way you are doing it, you are passing to expect
the result of calling model.get('z')
. But to test whether something is thrown, you have to pass a function to expect
, which expect
will call itself. The bind
method used above creates a new function which when called will call model.get
with this
set to the value of model
and the first argument set to 'z'
.
bind
的一个很好的解释可以在 这里.
A good explanation of bind
can be found here.
这篇关于Mocha/Chai expect.to.throw 没有捕捉到抛出的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!