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

时间:2015-01-15 19:44:00

标签: javascript angularjs unit-testing jasmine

我遇到问题单元测试以下方法:

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

我已经编写了以下因此错误而失败的单元测试(TypeError:无法读取属性'未定义的搜索):

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吗?对于我的生活,我无法弄清楚这一点。

2 个答案:

答案 0 :(得分:21)

这是因为你的mock不能返回位置对象以便能够链接。使用Jasmine 2.0,您可以将模拟更改为:

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

答案 1 :(得分:0)

尝试:

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

否则你会在模拟而不是$ location上调用搜索