为什么在angularjs中使用$ location和$ route时我的单元测试失败了?

时间:2015-02-07 10:40:35

标签: angularjs unit-testing routes location karma-jasmine

在向控制器添加$ location和$ route后,我的所有单元测试都失败了。我尝试在网上找到一些答案后嘲笑他们,但它似乎没有改变任何东西。

控制器:

 myAppModule.controller('addUserCtrl', ['$scope', '$http', '$location',
      function ($scope, $http, $location) {
        $scope.addNewUser = function(user){
          $http.post('url/users', user);
          $location.path('/')
        }
      }
    ]);

myAppModule.controller('usersCtrl', ['$scope', '$http', '$route',
  function ($scope, $http, $route) {
    $http.get('url/users').success(function(data){
      $scope.users = data;
    })

    $scope.delete = function(id){
      $http.delete('url/users/' + id).success(function(){
        $route.reload();
      })
    }
  }
]);

addUserCtrl的测试设置:

describe('addUserCtrl controller', function(){

  beforeEach(module('myAppModule'));

  var scope, ctrl, $httpBackend;

  var user = [
    {
      "username": "Zoltan",
      "email": "Zoltan@Z.com"
    }
  ]

  beforeEach(inject(function(_$httpBackend_, $rootScope, $controller) {
    $httpBackend = _$httpBackend_;
    $httpBackend.expectPOST('url/users', user).
    respond(200, 'Done');
    scope = $rootScope.$new();
    ctrl = $controller('addUserCtrl', { $scope: scope });
  }));

some test here

})

usersCtrl的测试设置:

    describe('UsersCtrl', function(){

      beforeEach(module('myAppModule'));

      var scope, ctrl, $httpBackend;

      var users = [
        {
          "username": "Zoltan",
          "email": "Zoltan@Z.com",
          "id": 1
        },
        {
          "username": "Aria123",
          "email": "aria@aria.com",
          "id": 2
        }
      ]

      beforeEach(inject(function(_$httpBackend_, $rootScope, $controller) {
       $httpBackend = _$httpBackend_;
       $httpBackend.expectGET('url/users').respond(users);
       scope = $rootScope.$new();
       ctrl = $controller('usersCtrl', { $scope:scope });
     }));

some test here

   })

我可以在测试中写任何内容,但是他们没有遇到这个错误:

TypeError: undefined is not a function
        at $LocationProvider.$get (/home/elena/projects/myAppInAngularJS/app/bower_components/angular/angular.js:11305:34)

0 个答案:

没有答案