我遇到问题让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.
答案 0 :(得分:293)
您必须将功能传递给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.'));
您采用的方式是:expect
调用model.get('z')
的结果。但是为了测试是否抛出了某些东西,你必须将一个函数传递给expect
,expect
将调用它自己。上面使用的bind
方法会创建一个新函数,调用时会调用model.get
,this
设置为model
,第一个参数设置为'z'
bind
可以找到{{1}}的一个很好的解释。
答案 1 :(得分:151)
作为this answer says,您也可以将代码包装在这样的匿名函数中:
expect(function(){
model.get('z');
}).to.throw('Property does not exist in model schema.');
答案 2 :(得分:74)
如果您已经在使用ES6 / ES2015,那么您也可以使用箭头功能。它与使用普通匿名函数基本相同,但更短。
expect(() => model.get('z')).to.throw('Property does not exist in model schema.');
答案 3 :(得分:61)
这个问题有许多重复,包括不提Chai断言库的问题。以下是一起收集的基础知识:
断言必须调用函数,而不是立即进行评估。
assert.throws(x.y.z);
// FAIL. x.y.z throws an exception, which immediately exits the
// enclosing block, so assert.throw() not called.
assert.throws(()=>x.y.z);
// assert.throw() is called with a function, which only throws
// when assert.throw executes the function.
assert.throws(function () { x.y.z });
// if you cannot use ES6 at work
function badReference() { x.y.z }; assert.throws(badReference);
// for the verbose
assert.throws(()=>model.get(z));
// the specific example given.
homegrownAssertThrows(model.get, z);
// a style common in Python, but not in JavaScript
您可以使用任何断言库检查特定错误:
assert.throws(() => x.y.z);
assert.throws(() => x.y.z, ReferenceError);
assert.throws(() => x.y.z, ReferenceError, /is not defined/);
assert.throws(() => x.y.z, /is not defined/);
assert.doesNotThrow(() => 42);
assert.throws(() => x.y.z, Error);
assert.throws(() => model.get.z, /Property does not exist in model schema./)
should.throws(() => x.y.z);
should.throws(() => x.y.z, ReferenceError);
should.throws(() => x.y.z, ReferenceError, /is not defined/);
should.throws(() => x.y.z, /is not defined/);
should.doesNotThrow(() => 42);
should.throws(() => x.y.z, Error);
should.throws(() => model.get.z, /Property does not exist in model schema./)
expect(() => x.y.z).to.throw();
expect(() => x.y.z).to.throw(ReferenceError);
expect(() => x.y.z).to.throw(ReferenceError, /is not defined/);
expect(() => x.y.z).to.throw(/is not defined/);
expect(() => 42).not.to.throw();
expect(() => x.y.z).to.throw(Error);
expect(() => model.get.z).to.throw(/Property does not exist in model schema./);
您必须处理“逃避”的例外情况。测试
it('should handle escaped errors', function () {
try {
expect(() => x.y.z).not.to.throw(RangeError);
} catch (err) {
expect(err).to.be.a(ReferenceError);
}
});
一开始看起来很混乱。就像骑自行车一样,它只需点击一下即可。永远一旦它点击。
答案 4 :(得分:4)
因为您依赖此上下文 :
你必须使用以下选项之一:
绑定上下文
// wrap the method or function call inside of another function
expect(function () { cat.meow(); }).to.throw(); // Function expression
expect(() => cat.meow()).to.throw(); // ES6 arrow function
// bind the context
expect(cat.meow.bind(cat)).to.throw(); // Bind
答案 5 :(得分:1)
另一种可能的实现,比.bind()解决方案更麻烦,但是可以帮助您指出Expect()需要一个为覆盖的函数提供this
上下文的函数,您可以使用call()
,例如
expect(function() {model.get.call(model, 'z');}).to.throw('...');
答案 6 :(得分:0)
我找到了解决它的好方法:
// The test, BDD style
it ("unsupported site", () => {
The.function(myFunc)
.with.arguments({url:"https://www.ebay.com/"})
.should.throw(/unsupported/);
});
// The function that does the magic: (lang:TypeScript)
export const The = {
'function': (func:Function) => ({
'with': ({
'arguments': function (...args:any) {
return () => func(...args);
}
})
})
};
比我的旧版本更具可读性:
it ("unsupported site", () => {
const args = {url:"https://www.ebay.com/"}; //Arrange
function check_unsupported_site() { myFunc(args) } //Act
check_unsupported_site.should.throw(/unsupported/) //Assert
});