【问题标题】:Mocha testing schema with .validate() does not return带有 .validate() 的摩卡测试模式不返回
【发布时间】: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


    【解决方案1】:

    问题是由于我在描述中更新了一个中间件,这个中间件异步调用数据库,因此我只是在测试模式并且无法在没有连接的情况下查询数据库。

    我认为这是由于连接错误造成的,需要超过 2 秒才能抛出。

    【讨论】:

    • 您使用的解决方案是什么?我现在也在为此苦苦挣扎
    猜你喜欢
    • 1970-01-01
    • 2014-04-06
    • 1970-01-01
    • 2015-03-21
    • 2019-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多