对如何使用 mocha + chai 正确断言 keystoneJS 模型保存错误感到困惑
confused on how to properly assert a keystoneJS model save error with mocha + chai
似乎无法找出正确的模式来抛出并且 Chai 断言 keystonejs (v 3.x) 模型错误:
我得到了一个带有单个 "unique : true " 字符串参数的简单模型:
我的模型 {"uri":"http://google.com"}。
此测试旨在断言错误,因为存在具有相同 uri 参数值的现有文档 - 并且
这是我的测试:
it('should throw an error when create with duplicate unique uri param', function(done) {
var myList = keystone.list('myModel');
expect(function(){
var newObj = new myList.model({
uri: 'http://google.com'
});
newObj.save(function(err,doc){
console.log(err); //properly instantiates MongoError: E11000 duplicate key error index:
if (err) throw new Error(err);
});
}).to.throw();
done();
});
此测试失败并显示:
1) MyModel should throw an error when create with duplicate unique uri param:
AssertionError: expected [Function] to throw an error
关于正确的模式有什么想法吗?
这里有一个不错的模式:
...
newObj.save(function(err,doc){
if (err) {
expect(err).to.match(/duplicate key/);
done();
}
else {
throw new Error("doc should not have been created");
}
});
似乎无法找出正确的模式来抛出并且 Chai 断言 keystonejs (v 3.x) 模型错误:
我得到了一个带有单个 "unique : true " 字符串参数的简单模型: 我的模型 {"uri":"http://google.com"}。 此测试旨在断言错误,因为存在具有相同 uri 参数值的现有文档 - 并且
这是我的测试:
it('should throw an error when create with duplicate unique uri param', function(done) {
var myList = keystone.list('myModel');
expect(function(){
var newObj = new myList.model({
uri: 'http://google.com'
});
newObj.save(function(err,doc){
console.log(err); //properly instantiates MongoError: E11000 duplicate key error index:
if (err) throw new Error(err);
});
}).to.throw();
done();
});
此测试失败并显示:
1) MyModel should throw an error when create with duplicate unique uri param:
AssertionError: expected [Function] to throw an error
关于正确的模式有什么想法吗?
这里有一个不错的模式:
...
newObj.save(function(err,doc){
if (err) {
expect(err).to.match(/duplicate key/);
done();
}
else {
throw new Error("doc should not have been created");
}
});