Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spying on a constructor using Jasmine

I am using Jasmine to test if certain objects are created and methods are called on them.

I have a jQuery widget that creates flipcounter objects and calls the setValue method on them. The code for flipcounter is here: https://bitbucket.org/cnanney/apple-style-flip-counter/src/13fd00129a41/js/flipcounter.js

The flipcounters are created using:

var myFlipCounter = new flipCounter("counter", {inc: 23, pace: 500}); 

I want to test that the flipcounters are created and the setValue method is called on them. My problem is that how do I spy on these objects even before they are created? Do I spy on the constructor and return fake objects? Sample code would really help. Thanks for your help! :)

Update:

I've tried spying on the flipCounter like this:

myStub = jasmine.createSpy('myStub'); spyOn(window, 'flipCounter').andReturn(myStub);  //expectation expect(window.flipCounter).toHaveBeenCalled(); 

Then testing for the setValue call by flipCounter:

spyOn(myStub, 'setValue');  //expectation expect(myStub.setValue).toHaveBeenCalled(); 

the first test for initializing flipCounter is fine, but for testing the setValue call, all I'm getting is a 'setValue() method does not exist' error. Am I doing this the right way? Thanks!

like image 800
gerky Avatar asked Feb 19 '12 07:02

gerky


People also ask

How do I spy on object Jasmine?

In Jasmine, you can do anything with a property spy that you can do with a function spy, but you may need to use different syntax. Use spyOnProperty to create either a getter or setter spy. it("allows you to create spies for either type", function() { spyOnProperty(someObject, "myValue", "get").

What does Jasmine spyOn do?

Jasmine spies are used to track or stub functions or methods. Spies are a way to check if a function was called or to provide a custom return value. We can use spies to test components that depend on service and avoid actually calling the service's methods to get a value.


1 Answers

flipCounter is just another function, even if it also happens to construct an object. Hence you can do:

var cSpy = spyOn(window, 'flipCounter'); 

to obtain a spy on it, and do all sorts of inspections on it or say:

var cSpy = spyOn(window, 'flipCounter').andCallThrough(); var counter = flipCounter('foo', options); expect(cSpy).wasCalled(); 

However, this seems overkill. It would be enough to do:

var myFlipCounter = new flipCounter("counter", options); expect(myFlipCounter).toBeDefined(); expect(myFlipCounter.getValue(foo)).toEqual(bar); 
like image 185
ggozad Avatar answered Sep 27 '22 21:09

ggozad