使用jasmine.spyOn用于mongoose模式方法
我无法让茉莉间谍为我的mongoose文件工作。 我有一个方法设置在我的用户架构像这样:
User.methods.doSomething = function() { // implementation }
用户是我正在testing的模型的依赖关系,我想确保doSomething被正确调用。 在我的testing中,我有这样的东西:
spyOn(User.schema.methods, 'doSomething')
如果我注销User.schema.methods.doSomething我得到我期望的function,但是当我运行调用该方法的代码原始实现被调用,而不是间谍。 我也不能这样做:
spyOn(userInstance, 'doSomething')
在我的testing中,userInstance没有被暴露,我真的想避免暴露它。 本质上,我想在用户文档(实例?)原型上设置一个间谍。 那可能吗?
Mongoose正在将模式中定义的方法复制到模型原型,并且只使用这些方法。 所以即使
User.schema.methods.doSomething === User.prototype.doSomething
如果你设置:
spyOn(User.schema.methods, 'doSomething')
它不会被调用 – User.prototype.doSomething
会。 你的猜测是对的,你应该使用:
spyOn(User.prototype, 'doSometing');
如果你想在build立间谍之后调用原始的方法,那么不要忘记使用and.callThrough
调用。
不幸的是,我无法让spyOn
在模型原型上工作。 这可能是因为我的“模式”实际上是一个mongoose子文件。
相反,我select了代理function,而不是我的间谍。 这是一个额外的函数调用,这有点烦人,但它的工作。
// index.js Controller._performClone = function(doc) { return doc.clone(); }; Controller.clone = function(id) { var child = parent.children.id(req.params.id); return Controller._performClone(child); }; // spec.js describe('Cloning', function() { it('should clone a document', function(done) { spyOn(Controller, '_performClone').and.returnValue('cloned'); var rtn = Controller.clone('1'); expect(rtn).toBe('cloned'); // `correctChild` is the one you expect with ID '1' expect(Controller._performClone).toHaveBeenCalledWith(correctChild); }); });