I have a function
var data = {}; var myFunc = function() { data.stuff = new ClassName().doA().doB().doC(); };
I'd like to test that doA
, doB
, and doC
were all called.
I tried spying on the instance methods like this
beforeEach(function() { spyOn(ClassName, 'doA'); }; it('should call doA', function() { myFunc(); expect(ClassName.doA).toHaveBeenCalled(); });
but that just gives me a "doA() method does not exist" error.
Any ideas?
There are two ways to create a spy in Jasmine: spyOn() can only be used when the method already exists on the object, whereas jasmine. createSpy() will return a brand new function: //spyOn(object, methodName) where object. method() is a function spyOn(obj, 'myMethod') //jasmine.
spyOn() spyOn() is inbuilt into the Jasmine library which allows you to spy on a definite piece of code. Let us create a new spec file “spyJasmineSpec. js” and another js file named as “spyJasmine.
spyOn() takes two parameters: the first parameter is the name of the object and the second parameter is the name of the method to be spied upon. It replaces the spied method with a stub, and does not actually execute the real method. The spyOn() function can however be called only on existing methods.
Using Jasmine spies to mock code Jasmine spies are easy to set up. You set the object and function you want to spy on, and that code won't be executed. In the code below, we have a MyApp module with a flag property and a setFlag() function exposed. We also have an instance of that module called myApp in the test.
Where you went wrong was your understanding of how to refer to methods in JavaScript in a static context. What your code is actually doing is spying on ClassName.doA
(that is, the function attached to the ClassName
constructor as the property doA
, which is not what you want).
If you want to detect when that method gets called on any instance of ClassName
anywhere, you need to spy on the prototype.
beforeEach(function() { spyOn(ClassName.prototype, 'doA'); }); it('should call doA', function() { myFunc(); expect(ClassName.prototype.doA).toHaveBeenCalled(); });
Of course, this is assuming that doA
lives in the prototype chain. If it's an own-property, then there is no technique that you can use without being able to refer to the anonymous object in myFunc
. If you had access to the ClassName
instance inside myFunc
, that would be ideal, since you could just spyOn
that object directly.
P.S. You should really put "Jasmine" in the title.
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