node.js - Mongoose 文档 : Execute hook manually for testing

标签 node.js testing mongoose mongoose-schema

我想测试一些在 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/

相关文章:

selenium - 在 Selenium 中针对单个任务在有头和 headless 之间切换

ruby-on-rails - 在 RSpec 中为 Gem 编写测试

node.js - Mongoose 更新深度数组

node.js - 如何通过 find 函数检查 mongoose 中是否存在和为空?

node.js - 将 Google App Engine 上的 Mongoose 连接到 mlab

javascript - 找不到 Socket.io 404

javascript - 用于用户事件的 Node + Github webhook

javascript - 使用 handlebars.js 显示 JSON 数据

javascript - 如何使用 testcafe 打印 promise 的内部文本?

node.js - Swagger UI 不发送 url 参数