我正在尝试创建一个简单的单元测试来测试我的表演功能。
我收到以下错误:
TypeError: Object #<Object> has no method 'show'
看来这$rootScope不是控制器的范围吗?
$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'); })); });
希望这可以帮助!