Spy on a method of an object created in the function you're testing.

4,152 views
Skip to first unread message

mobi...@gmail.com

unread,
Nov 25, 2013, 4:51:31 PM11/25/13
to jasmi...@googlegroups.com

I have a question about using a spy in the following situation.


Let's say I'm testing function myClass.blah. Within that method, I'm instantiating ha of type Ha. I'd like to spy on ha.hoo method to make sure it was called.


MyClass.prototype.blah() = function { this.ha = new Ha(); this.ha.hoo(); };



Below is an obviously incorrect way of doing this, but illustrates what I'd like to do. What would be the correct way to it?


it('setupDetection', function () { var myClass = new MyClass();

spyOn(myClass.ha 'hoo'); //This understandably won't work as myClass.ha does not exist yet. How do I spy on it?

myClass.blah();

expect(myClass.ha.hoo).toHaveBeenCalled(); });



I'm fairly new to Jasmine. Any help would be much appreciated.


Thanks, JC






Davis W. Frank

unread,
Nov 25, 2013, 5:04:08 PM11/25/13
to jasmi...@googlegroups.com
You're having pain because MyClass is depending on an instance of Ha. That dependency is the challenge. You're not unit testing MyClass and Ha at the same time. Icky.

One way would be to inject the dependency into blah like this:

MyClass.prototype.blah = function( haFactory ) {
  var factory = haFactory || function() { return new Ha();};

  this.ha = factory();
  this.ha.hoo(); 
};

Once you've done this, your test can be more like this:

it('setupDetection', function(){ var myClass = new MyClass(),

ha = new Ha(),

haFactory = function() { return ha; };

spyOn(ha, "hoo");

myClass.blah(haFactory);

expect(ha.hoo).toHaveBeenCalled();

});


It's a subtle difference, but one that gives you the flexibility of what you want under test while still doing the right thing at runtime. You can imagine further refinements like passing in the factory to the constructor. Or remodel your system with different dependencies.

But the good rule of thumb is "only be testing one object at a time".

--dwf 




--
You received this message because you are subscribed to the Google Groups "Jasmine" group.
To unsubscribe from this group and stop receiving emails from it, send an email to jasmine-js+...@googlegroups.com.
To post to this group, send email to jasmi...@googlegroups.com.
Visit this group at http://groups.google.com/group/jasmine-js.
For more options, visit https://groups.google.com/groups/opt_out.



--
thx,
--dwf

mobiDevJC

unread,
Nov 25, 2013, 5:42:29 PM11/25/13
to jasmi...@googlegroups.com
Thanks for the prompt response and suggestions. I ended up doing a variation of this by passing the factory in the  constructor for MyClass as you mentioned in further refinements. 


 JC
Reply all
Reply to author
Forward
0 new messages