【发布时间】:2018-11-20 00:11:11
【问题描述】:
目前我正在尝试编写一些架构测试,并且我有以下架构:
const ItemSchema = mongoose.Schema({
_id : mongoose.Schema.Types.ObjectId,
price : {type : Number},
name : {type : String, required : true, trim : true},
urlPath : {type : String, required : true, unique : true, trim : true},
creationDate : {type : Date, default : Date.now},
lastModDate : {type : Date, default : Date.now},
}, {
toJSON: { virtuals: true }
});
urlPath 和 name 属性是必需的。
我的测试文件如下所示:
describe('validation', () => {
it('should be invalid if name is missing', function(done){
let item = new Item({urlPath : "item-1-urlPath"});
item.validate(function(err){
if(!err) done('should not be here');
expect(err.name).to.eql('ValidationError');
expect(err.errors).to.have.property('name');
done();
});
})
})
我总是收到这个错误:
超过 2000 毫秒的超时。对于异步测试和钩子,确保调用了“done()”;如果返回 Promise,请确保它已解决。
但是当我像这样验证缺少 urlPath 时:
let item = new Item({name : "item-1"});
一切似乎都很好
更新
我正在使用的中间件(答案中的描述)
ItemSchema.pre('validate', async function() {
var item = this;
let urlPath = item.urlPath;
// only if it has been modified (or is new)
if (!item.isModified('urlPath')) return Promise.resolve();
urlPath = await [HERE_I_AM_CALLING_A_PROMISE_FUNCTION]
item.urlPath = urlPath;
});
- nodejs:8.1.1
- 猫鼬:5.1.3
- 打字稿:2.9.1
- 系统:ubuntu 16.04
【问题讨论】:
标签: node.js typescript mongoose mocha.js