我想测试一些在 Mongoose pre
save
Hook 中执行的文档转换。简化示例:
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');
如何手动执行这个钩子(Hook)?
最佳答案
好的,这就是我们最后所做的。我们将 $__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
Hook 显然仍会被调用。
testDoc.save(function(err, doc) {
expect(doc.property).to.eql('foo_modified');
done();
});
任务完成。
关于node.js - Mongoose 文档 : Execute hook manually for testing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47104099/