I'm having a problem unit testing the following method:
$scope.changeLocation = function (url) {
$location.path(url).search({ ref: "outline" });
};
I've written the following unit test that currently fails with this error (TypeError: Cannot read property 'search' of undefined):
var $locationMock = { path: function () { }, search: function () { } };
it('changeLocation should update location correctly', function () {
$controllerConstructor('CourseOutlineCtrl', { $scope: $scope, $location: $locationMock });
var url = "/url/";
spyOn($locationMock, "path");
spyOn($locationMock, "search");
$scope.changeLocation(url);
expect($locationMock.search).toHaveBeenCalledWith({ ref: "outline" });
expect($locationMock.path).toHaveBeenCalledWith(url);
});
If I change my function to the following, the test passes:
$scope.changeLocation = function (url) {
$location.path(url);
$location.search({ ref: "outline" });
};
How do I unit test this method when I'm using method chaining? Do I need to setup my $locationMock differently? For the life of me I cannot figure this out.
That is because your mock does not return location object to be able to chain through. Using Jasmine 2.0 you can change your mock to:
and
or add:
Or just create a spy object (less code):
and
try :
Else you'r calling search on a mock not $location