如何使用 Jasmine 对链式方法进行单元测试

How to unit test a chained method using Jasmine

我在对以下方法进行单元测试时遇到问题:

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

我编写了以下单元测试,但目前因此错误而失败(TypeError:无法读取未定义的 属性 'search'):

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);
    });

如果我将函数更改为以下内容,则测试通过:

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

当我使用方法链时如何对这个方法进行单元测试?我需要以不同的方式设置我的 $locationMock 吗?我这辈子都弄不明白。

尝试:

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

否则你是在模拟而不是 $location

上调用搜索

那是因为您的 mock return 位置对象无法链接。使用 Jasmine 2.0,您可以将 mock 更改为:

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

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

或添加:

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

或者只创建一个间谍对象(更少的代码):

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

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