I'm having trouble getting jasmine spies to work for my mongoose documents. I have a method set up in my User schema like so:
User.methods.doSomething = function() {
// implementation
}
User is a dependency of the model I'm currently testing and I want to ensure that doSomething is being called correctly. In my tests I have something like:
spyOn(User.schema.methods, 'doSomething')
If I log out User.schema.methods.doSomething I get the function I expect but when I run the code that calls that method the original implementation is invoked and not the spy. Also I can't do:
spyOn(userInstance, 'doSomething')
In my tests as the userInstance isn't being exposed and I really want to avoid exposing it. Essentially I want to set up a spy on the User document (instance?) prototype. Is that possible?
Mongoose is copying the methods defined in the schema to the model prototype and only those methods are used. So even though
User.schema.methods.doSomething === User.prototype.doSomething
if you set:
spyOn(User.schema.methods, 'doSomething')
it won't get called - User.prototype.doSomething
will. Your guess was right, you should just use:
spyOn(User.prototype, 'doSometing');
Don't forget to use and.callThrough
if you want to have the original method called after setting up the spy (I fell for that).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With