unit-testing – 如何使用$location服务单元测试angularjs控制器

我试图创建一个简单的单元测试,测试我的show函数。

我得到以下错误:

TypeError: Object #<Object> has no method 'show'

似乎$ rootScope不是控制器的范围?

这是我的控制器:

function OpponentsCtrl($scope, $location) {
    $scope.show = function(url) {
        $location.path(url);
    }
}
OpponentsCtrl.$inject = ['$scope', '$location'];

这里是我的控制器单元测试:

describe('OpponentsCtrl', function() {
    beforeEach(module(function($provide) {
        $provide.factory('OpponentsCtrl', function($location){
            // whatever it does...
        });
    }));

    it('should change location when setting it via show function', inject(function($location, $rootScope, OpponentsCtrl) {
        $location.path('/new/path');
        $rootScope.$apply();
        expect($location.path()).toBe('/new/path');

        $rootScope.show('/test');
        expect($location.path()).toBe('/test');
    }));
});
最佳答案
为什么不使用spyOn函数?

describe('OpponentsCtrl', function() {

    var location;

    beforeEach(module(function($provide) {
        $provide.factory('OpponentsCtrl', function($location){
            location = $location;
        });
    }));

    it('should change location when setting it via show function', inject(function() {    
        spyOn(location, 'path');    
        expect(location.path).toHaveBeenCalledWith('/new/path');
    }));
});

希望这可以帮助!

转载注明原文:unit-testing – 如何使用$location服务单元测试angularjs控制器 - 代码日志