我试图创建一个简单的单元测试,测试我的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函数?
原文链接:https://www.f2er.com/angularjs/145624.htmldescribe('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'); })); });
希望这可以帮助!