Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Jasmine's spyOn() allow the spied on function to be executed?

Does Jasmine's spyOn() method allow the spied on function to be executed, or does it, kind of - intercept the invocation when the spied method is (about to get) invoked, and returns true.

PS: Could anyone point me to the explanation of spyOn()'s inner workings?

like image 789
Nikolay Melnikov Avatar asked Oct 20 '22 22:10

Nikolay Melnikov


1 Answers

Spy :

A spy can pretend to be a function or an object that you can use while writing unit test code to examine behavior of functions/objects

var Person = function() {};
Dictionary.prototype.FirstName = function() {
return "My FirstName";
};
Dictionary.prototype.LastName = function() {
return "My LastName";
};
Person.prototype.MyName = function() {
return FirstName() + " " + LastName();
};

Person.prototype.MyLocation = function() {
Return ”some location”;
};

describe("Person", function() {
    it('uses First Name and Last Name for MyName', function() {
        var person = new Person;
        spyOn(person , "FirstName"); 
        spyOn(person, "LastName"); 
        person.MyName();
        expect(person.FirstName).toHaveBeenCalled(); 
        expect(person.LastName).toHaveBeenCalled(); 
    });
});

Through SpyOn you can know whether some function has been / has not been called

expect(person. MyLocation).not.toHaveBeenCalled();

You can ensure that a spy always returns a given value and test it

spyOn(person, " MyName ").andReturn("My FirstNameMy LasttName ");
var result = person.MyName();
expect(result).toEqual("My FirstName  My LasttName ");

Spies can call through to a fake function

it("can call a fake function", function() {
var fakeFun = function() {
alert("I am a spy!”);
return "hello";
};
var person = new person();
spyOn(person, "MyName").andCallFake(fakeFun);
person. MyName (); // alert
})

You can even create a NEW spy function or object and make use of it

it("can have a spy function", function() {
var person = new Person();
person.StreetAddress = jasmine.createSpy("Some Address");
person. StreetAddress ();
expect(person. StreetAddress).toHaveBeenCalled();
});
like image 137
Rabi Avatar answered Oct 22 '22 22:10

Rabi