Mongoose文档:手动执行hook进行测试

Mongoose document: Execute hook manually for testing

我想测试一些在 Mongoose pre save 挂钩中执行的文档转换。简化示例:

mySchema.pre('save', function(callback) {
  this.property = this.property + '_modified';
  callback();
});

测试:

var testDoc = new MyDocument({ property: 'foo' });
// TODO -- how to execute the hook?
expect(testDoc.property).to.eql('foo_modified');

如何手动执行这个钩子?

好的,这就是我们最后所做的。我们用无操作实现替换了 $__save 函数:

// overwrite the $__save with a no op. function, 
// so that mongoose does not try to write to the database
testDoc.$__save = function(options, callback) {
  callback(null, this);
};

这可以防止访问数据库,但 pre 挂钩显然仍会被调用。

testDoc.save(function(err, doc) {
  expect(doc.property).to.eql('foo_modified');
  done();
});

任务完成。

从 Mongoose 5.9 开始,使用 $__save 覆盖似乎不起作用,因此这里有一个不需要您直接调用 save() 方法的替代方法:

const runPreSaveHooks = async (doc) => {
  return new Promise((resolve, reject) => {
    doc.constructor._middleware.execPre("save", doc, [doc], (error) => {
      error ? reject(error) : resolve(doc);
    });
  });
};

await runPreSaveHooks(testDoc);
expect(testDoc.property).to.eql('foo_modified');