How to unit test a chained method using Jasmine

爷,独闯天下 提交于 2019-12-03 19:30:52

问题


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.


回答1:


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:

var $locationMock = { path: function () { return $locationMock; }, 
                      search: function () { return $locationMock; } };

and

spyOn($locationMock, "path").and.callThrough();
spyOn($locationMock, "search").and.callThrough(); //if you are chaining from search

or add:

spyOn($locationMock, "path").and.returnValue($locationMock);
spyOn($locationMock, "search").and.returnValue($locationMock); //if you are chaining from search

Or just create a spy object (less code):

var $locationMock = jasmine.createSpyObj('locationMock', ['path', 'search']);

and

$locationMock.path.and.returnValue($locationMock);
$locationMock.search.and.returnValue($locationMock); //if you are chaining from search



回答2:


try :

spyOn($locationMock, "path").and.callThrough();

Else you'r calling search on a mock not $location



来源:https://stackoverflow.com/questions/27971729/how-to-unit-test-a-chained-method-using-jasmine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!