How to unit test a chained method using Jasmine

前端 未结 2 810
陌清茗
陌清茗 2020-12-31 11:28

I\'m having a problem unit testing the following method:

 $scope.changeLocation = function (url) {
        $location.path(url).search({ ref: \"outline\" });
         


        
2条回答
  •  梦谈多话
    2020-12-31 12:19

    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
    

提交回复
热议问题