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!
My version to test a constructor is to spy on the prototype:
I would suggest using
jasmine.createSpyObj()
when you want to mock objects with properties that need to be spied on.This tests interactions with the expected
flipCounter
interface, without depending on theflipCounter
implementation.Don't know how to do this using jasmine mocks, but if you want powerful mocking/spy/stubs I recommend sinon.js, wich works very well with jasmine.
From docs:
With sinon.js you could create a mock of the flipCounter constructor that returns another spy.
Then assert that the constructor was called using constructorMock.calledWithNew(), and assert that the returned spy was called with returnedSpy.calledWith(arg1, arg2...).
You have to implement a fake constructor for
flipCounter
that sets thesetValue
property to a spy function. Let's say the function you want to test is this:Your spec should look like this:
The following does not rely on 'window'. Lets say this is the code you want to test -
Your test could be -
flipCounter
is just another function, even if it also happens to construct an object. Hence you can do:to obtain a spy on it, and do all sorts of inspections on it or say:
However, this seems overkill. It would be enough to do: