摩卡/柴期托.抛出不捕捉抛出的错误我有问题去拿柴氏的expect.to.throw在我的node.js应用程序的测试中工作。测试在抛出的错误上一直失败,但是如果我将测试用例包装在TRY和CATCH中,并断言捕获的错误,它就能工作。是吗?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.
3 回答
慕侠2389804
TA贡献1719条经验 获得超6个赞
断言必须调用函数,而不是立即计算。
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 workfunction badReference() { x.y.z }; assert.throws(badReference);
// for the verboseassert.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);
}});添加回答
举报
0/150
提交
取消
