Does Jasmine's spyOn () function provide the ability to trigger a watch function?

Does the Jasmine method use the spyOn()

spy trigger function or does it, sort of - intercepts the call when the called method is spied (about to receive) and returns true

.

PS: Can anyone point me to an explanation of the spyOn()

inner workings?

+3


source to share


2 answers


Spy:

A spy can pretend to be a function or object, which you can use when writing unit test code to study the 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 find out if some function was / was not called

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

      

You can ensure that the spy always returns the given value and checks it



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

      

Spies can jump 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 feature or spy object and use it

it("can have a spy function", function() {
var person = new Person();
person.StreetAddress = jasmine.createSpy("Some Address");
person. StreetAddress ();
expect(person. StreetAddress).toHaveBeenCalled();
});

      

+1


source


It just creates a mock (spy) object and injects it into the code under test.

It has three main purposes:



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


source







All Articles