[ jasmine ] spyOn(param, method).and.returnValue(whatever)

mock the function to return value

spyOn(param, method).and.returnValue(whateverReturnValue)

ref : http://tobyho.com/2011/12/15/jasmine-spy-cheatsheet/

By default, when you use spyOn with jasmine, it mocks that function and doesn’t actually execute anything within it. If you want to test further function calls within, you’ll need to call .andCallThrough()

describe("A spy, when configured to call through", function() {
var foo, bar, fetchedBar;

beforeEach(function() {
foo = {
setBar: function(value) {
bar = value;
},
getBar: function() {
return bar;
}
};

spyOn(foo, 'getBar').and.callThrough();

foo.setBar(123);
fetchedBar = foo.getBar();
});

it("tracks that the spy was called", function() {
expect(foo.getBar).toHaveBeenCalled();
});

it("should not affect other functions", function() {
expect(bar).toEqual(123);
});

it("when called returns the requested value", function() {
expect(fetchedBar).toEqual(123);
});
});

mock http request using $httpBackend

 beforeEach(inject(function(_$rootScope_, _$httpBackend_) {

$scope = _$rootScope_;

$httpBackend = _$httpBackend_;

$httpBackend.whenPATCH('/api/whatever/1').respond({})

}
$httpBackend.flush()

ref : https://docs.angularjs.org/api/ngMock/service/$httpBackend

compile directive

from $scope.params, $scope.form

var element = angular.element("<whatever-directive params1='params' form='form'></whatever-directive>")
$compile(element)($scope)
$scope.$apply()

expect(functionName).toHaveBeenCalledWith(“whatever”, “function”, “parameter”);

describe("A spy, when created manually", function() {
var whatAmI;

beforeEach(function() {
whatAmI = jasmine.createSpy('whatAmI');

whatAmI("I", "am", "a", "spy");
});

it("is named, which helps in error reporting", function() {
expect(whatAmI.and.identity()).toEqual('whatAmI');
});

it("tracks that the spy was called", function() {
expect(whatAmI).toHaveBeenCalled();
});

it("tracks its number of calls", function() {
expect(whatAmI.calls.count()).toEqual(1);
});

it("tracks all the arguments of its calls", function() {
expect(whatAmI).toHaveBeenCalledWith("I", "am", "a", "spy");
});

it("allows access to the most recent call", function() {
expect(whatAmI.calls.mostRecent().args[0]).toEqual("I");
});
});

ref : https://stackoverflow.com/questions/17705121/jasmine-how-to-spy-on-a-function-call-within-a-function,

https://jasmine.github.io/2.0/introduction.html

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s