Mongoose文件:手动执行钩子进行testing

我想testing一下在Mongoose pre save hook中执行的文档转换。 简单的例子:

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

testing:

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

我怎样才能手动执行这个钩子?

好的,这是我们在最后做的。 我们使用no操作实现replace了$__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(); }); 

任务完成。