带有 .validate() 的 Mocha 测试模式不 return
Mocha testing schema with .validate() does not return
目前我正在尝试编写一些模式测试,我有以下模式:
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();
});
})
})
我总是遇到这个错误:
Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.
但是当我像这样验证缺少 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;
});
- 节点:8.1.1
- 猫鼬:5.1.3
- 打字稿:2.9.1
- 系统:ubuntu16.04
问题是由于我在描述中更新的一个中间件引起的,这个中间件正在异步调用数据库,因此我只是在测试架构,无法在没有连接的情况下查询数据库。
我认为这是由于连接错误导致的,需要超过 2 秒才能抛出。
目前我正在尝试编写一些模式测试,我有以下模式:
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();
});
})
})
我总是遇到这个错误:
Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.
但是当我像这样验证缺少 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;
});
- 节点:8.1.1
- 猫鼬:5.1.3
- 打字稿:2.9.1
- 系统:ubuntu16.04
问题是由于我在描述中更新的一个中间件引起的,这个中间件正在异步调用数据库,因此我只是在测试架构,无法在没有连接的情况下查询数据库。
我认为这是由于连接错误导致的,需要超过 2 秒才能抛出。