Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using jasmine.spyOn for mongoose schema methods

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?

like image 523
matt.kauffman23 Avatar asked Apr 29 '14 23:04

matt.kauffman23


1 Answers

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).

like image 95
FatFisz Avatar answered Sep 28 '22 18:09

FatFisz