AngularJS错误:意外请求(不再需要请求)

cvk*_*k10 7 unit-testing jasmine angularjs

在我的AngularJS应用程序中,我无法弄清楚如何进行单元测试,然后一个承诺的执行会改变location.url.我有一个函数,登录,调用服务,AuthenticationService.它返回promise,而then promise的执行会改变location.url.

这是控制器AuthCtrl:

angular
  .module('bloc1App')
  .controller('AuthCtrl', ['$scope', '$http','$location', 'AuthenticationService',
  function($scope, $http, $location, AuthenticationService) { 

   this.AuthenticationService = AuthenticationService;
   var self = this;

  $scope.login = function(username, password){
    self.AuthenticationService
      .login(username, password)
      .then(function(){
        $location.url('/tasks');
      });
  };
 }
]);
Run Code Online (Sandbox Code Playgroud)

这是我在单元测试中的尝试:

    describe('Controller: AuthCtrl', function () {

      var scope,
          location,
          route,
          q,
          rootScope,
          AuthCtrl;

      beforeEach(module('bloc1App'));

      beforeEach(inject(function($controller, $rootScope, $location, $route, $q) {
        scope = $rootScope.$new();
        q = $q;
        rootScope = $rootScope;
        location = $location;
        route = $route;

      AuthCtrl = $controller('AuthCtrl', {
         $scope: scope,
         $route: route,
         $location: location
      });

    }));

    it('login should redirect user to tasks view', function(){
      var deferred = q.defer();
      spyOn(AuthCtrl.AuthenticationService, 'login').andReturn(deferred.promise);
      spyOn(location, 'url');
      scope.login('foo', 'foo');
      deferred.resolve();
      scope.$apply();
      expect(location.url).toHaveBeenCalledWith('/tasks');
    });
   });
Run Code Online (Sandbox Code Playgroud)

当我运行此测试时,我收到此错误.如果我使用rootScope,我会得到同样的错误.$ apply()代替:

Error: Unexpected request: GET views/AuthView.html
No more request expected
Run Code Online (Sandbox Code Playgroud)

当我取出范围.$ apply()时,我收到此错误:

Expected spy url to have been called with [ '/tasks' ] but it was never called.
Run Code Online (Sandbox Code Playgroud)

有想法该怎么解决这个吗?这是我第一次单独测试一个承诺,我可能在概念上误解了如何做到这一点.

预先感谢您的帮助.

hon*_*n2a 4

当您使用 AngularJS 进行单元测试时,您实际上是在使用ngMock模块中的模拟服务而不是真实服务。在这种情况下,您的错误可能来自模拟$httpBackend,如果您希望测试的单元用于$http发送真实请求,则必须首先“启动”模拟。(我没有看到您的代码$http在任何地方使用,所以我猜测您没有在此处显示一部分。)

基本上,您需要告诉$httpBackend模拟您正在期待一个特定的请求$httpBackend.when(或者您可以使用$httpBackend.expect,如果您希望模拟检查该请求是否确实被调用)以及应该返回什么响应。

因此,您的错误与承诺无关,而与连接到服务器的测试单元有关。