Given the following code snippet, how would you create a Jasmine spyOn
test to confirm that doSomething
gets called when you run MyFunction
?
function MyFunction() {
var foo = new MyCoolObject();
foo.doSomething();
};
Here's what my test looks like. Unfortunately, I get an error when the spyOn
call is evaluated:
describe("MyFunction", function () {
it("calls doSomething", function () {
spyOn(MyCoolObject, "doSomething");
MyFunction();
expect(MyCoolObject.doSomething).toHaveBeenCalled();
});
});
Jasmine doesn't appear to recognize the doSomething
method at that point. Any suggestions?
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.
spyOn() spyOn() is inbuilt into the Jasmine library which allows you to spy on a definite piece of code.
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.
Alternatively, as Gregg hinted, we could work with 'prototype'. That is, instead of spying on MyCoolObject directly, we can spy on MyCoolObject.prototype.
describe("MyFunction", function () {
it("calls doSomething", function () {
spyOn(MyCoolObject.prototype, "doSomething");
MyFunction();
expect(MyCoolObject.prototype.doSomething).toHaveBeenCalled();
});
});
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