Nikolay Melnikov
Nikolay Melnikov

Reputation: 1395

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?

Upvotes: 5

Views: 3850

Answers (2)

Rabi
Rabi

Reputation: 2220

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();
});

Upvotes: 2

halilb
halilb

Reputation: 4115

It just creates a mock(spy) object and injects it to your tested code.

It has three main purposes:

  1. Testing your code if it calls spy: toHaveBeenCalled
  2. Testing your code if it calls with appropriate parameters: toHaveBeenCalledWith
  3. Testing your code for different return values from spy: and.callThrough

Upvotes: 1

Related Questions