如何在Angular单元测试中处理运行块?

Ada*_*ner 6 javascript unit-testing angularjs karma-runner

我的理解是,当您在Angular单元测试中加载模块时,run会调用该块.

我认为,如果你正在测试一个组件,你不会同时测试该run块,因为单元测试应该只测试一个单元.真的吗?

如果是这样,有没有办法阻止run块运行?我的研究让我认为答案是"不",并且run块在模块加载时总是运行,但也许有一种方法可以覆盖它.如果没有,我将如何测试该run块?

运行块:

function run(Auth, $cookies, $rootScope) {
  $rootScope.user = {};
  Auth.getCurrentUser();
}
Run Code Online (Sandbox Code Playgroud)

Auth.getCurrentUser:

getCurrentUser: function() {
  // user is logged in
  if (Object.keys($rootScope.user).length > 0) {
    return $q.when($rootScope.user);
  }
  // user is logged in, but page has been refreshed and $rootScope.user is lost
  if ($cookies.get('userId')) {
    return $http.get('/current-user')
      .then(function(response) {
        angular.copy(response.data, $rootScope.user);
        return $rootScope.user;
      })
    ;
  }
  // user isn't logged in
  else  {
    return $q.when({});
  }
}
Run Code Online (Sandbox Code Playgroud)

auth.factory.spec.js

describe('Auth Factory', function() {
  var Auth, $httpBackend, $rootScope, $cookies, $q;
  var user = {
    username: 'a',
    password: 'password',
  };
  var response = {
    _id: 1,
    local: {
      username: 'a',
      role: 'user'
    }
  };

  function isPromise(el) {
    return !!el.$$state;
  }

  beforeEach(module('mean-starter', 'ngCookies', 'templates'));
  beforeEach(inject(function(_Auth_, _$httpBackend_, _$rootScope_, _$cookies_, _$q_) {
    Auth = _Auth_;
    $httpBackend = _$httpBackend_;
    $rootScope = _$rootScope_;
    $cookies = _$cookies_;
    $q = _$q_;
  }));
  afterEach(function() {
    $httpBackend.verifyNoOutstandingExpectation();
    $httpBackend.verifyNoOutstandingRequest();
  });

  it('#signup', function() {
    $rootScope.user = {};
    $httpBackend.expectPOST('/users', user).respond(response);
    spyOn(angular, 'copy').and.callThrough();
    spyOn($cookies, 'put').and.callThrough();
    var retVal = Auth.signup(user);
    $httpBackend.flush();
    expect(angular.copy).toHaveBeenCalledWith(response, $rootScope.user);
    expect($cookies.put).toHaveBeenCalledWith('userId', 1);
    expect(isPromise(retVal)).toBe(true);
  });

  it('#login', function() {
    $rootScope.user = {};
    $httpBackend.expectPOST('/login', user).respond(response);
    spyOn(angular, 'copy').and.callThrough();
    spyOn($cookies, 'put').and.callThrough();
    var retVal = Auth.login(user);
    $httpBackend.flush();
    expect(angular.copy).toHaveBeenCalledWith(response, $rootScope.user);
    expect($cookies.put).toHaveBeenCalledWith('userId', 1);
    expect(isPromise(retVal)).toBe(true);
  });

  it('#logout', function() {
    $httpBackend.expectGET('/logout').respond();
    spyOn(angular, 'copy').and.callThrough();
    spyOn($cookies, 'remove');
    Auth.logout();
    $httpBackend.flush();
    expect(angular.copy).toHaveBeenCalledWith({}, $rootScope.user);
    expect($cookies.remove).toHaveBeenCalledWith('userId');
  });

  describe('#getCurrentUser', function() {
    it('User is logged in', function() {
      $rootScope.user = response;
      spyOn($q, 'when').and.callThrough();
      var retVal = Auth.getCurrentUser();
      expect($q.when).toHaveBeenCalledWith($rootScope.user);
      expect(isPromise(retVal)).toBe(true);
    });
    it('User is logged in but page has been refreshed', function() {
      $cookies.put('userId', 1);
      $httpBackend.expectGET('/current-user').respond(response);
      spyOn(angular, 'copy').and.callThrough();
      var retVal = Auth.getCurrentUser();
      $httpBackend.flush();
      expect(angular.copy).toHaveBeenCalledWith(response, $rootScope.user);
      expect(isPromise(retVal)).toBe(true);
    });
    it("User isn't logged in", function() {
      $rootScope.user = {};
      $cookies.remove('userId');
      spyOn($q, 'when').and.callThrough();
      var retVal = Auth.getCurrentUser();
      expect($q.when).toHaveBeenCalledWith({});
      expect(isPromise(retVal)).toBe(true);
    });
  });
});
Run Code Online (Sandbox Code Playgroud)

尝试1:

beforeEach(module('mean-starter', 'ngCookies', 'templates'));
beforeEach(inject(function(_Auth_, _$httpBackend_, _$rootScope_, _$cookies_, _$q_) {
  Auth = _Auth_;
  $httpBackend = _$httpBackend_;
  $rootScope = _$rootScope_;
  $cookies = _$cookies_;
  $q = _$q_;
}));
beforeEach(function() {
  spyOn(Auth, 'getCurrentUser');
});
afterEach(function() {
  expect(Auth.getCurrentUser).toHaveBeenCalled();
  $httpBackend.verifyNoOutstandingExpectation();
  $httpBackend.verifyNoOutstandingRequest();
});
Run Code Online (Sandbox Code Playgroud)

这不起作用.run加载模块时会运行该块,因此Auth.getCurrentUser()在设置间谍之前调用该块.

Expected spy getCurrentUser to have been called.
Run Code Online (Sandbox Code Playgroud)

尝试2:

beforeEach(inject(function(_Auth_, _$httpBackend_, _$rootScope_, _$cookies_, _$q_) {
  Auth = _Auth_;
  $httpBackend = _$httpBackend_;
  $rootScope = _$rootScope_;
  $cookies = _$cookies_;
  $q = _$q_;
}));
beforeEach(function() {
  spyOn(Auth, 'getCurrentUser');
});
beforeEach(module('mean-starter', 'ngCookies', 'templates'));
afterEach(function() {
  expect(Auth.getCurrentUser).toHaveBeenCalled();
  $httpBackend.verifyNoOutstandingExpectation();
  $httpBackend.verifyNoOutstandingRequest();
});
Run Code Online (Sandbox Code Playgroud)

这不起作用,因为Auth在我的app模块加载之前无法注入.

Error: [$injector:unpr] Unknown provider: AuthProvider <- Auth
Run Code Online (Sandbox Code Playgroud)

尝试3:

如你所见,这里有一个鸡蛋问题.我需要在模块加载之前注入Auth并设置间谍,但我不能,因为在加载模块之前无法注入Auth.

这篇博文提到了鸡蛋问题,并提供了一个有趣的潜在解决方案.作者建议我加载模块之前Auth手动创建我的服务.由于我正在创建服务,而不是注入它,我可以在加载模块之前完成它,我可以设置间谍.然后在加载模块时,它会使用这个创建的模拟服务.$provide

这是他的示例代码:

describe('example', function () {
    var loggingService;
    beforeEach(function () {
        module('example', function ($provide) {
            $provide.value('loggingService', {
                start: jasmine.createSpy()
            });
        });
        inject(function (_loggingService_) {
            loggingService = _loggingService_;
        });
    });
    it('should start logging service', function() {
        expect(loggingService.start).toHaveBeenCalled();
    });
});
Run Code Online (Sandbox Code Playgroud)

这个问题是,我需要我的Auth服务!我只想使用模拟run块作为块; 我需要Auth其他地方的真实服务,所以我可以测试它.

我想我可以使用创建实际Auth服务$provide,但这感觉不对.


最后的问题 - 对于我最终用来处理这个run块问题的任何代码,我有没有办法将它解压出来,所以我不必为每个spec文件重新编写它?我能想到的唯一方法就是使用某种全局功能.


auth.factory.js

angular
  .module('mean-starter')
  .factory('Auth', Auth)
;

function Auth($http, $state, $window, $cookies, $q, $rootScope) {
  return {
    signup: function(user) {
      return $http
        .post('/users', user)
        .then(function(response) {
          angular.copy(response.data, $rootScope.user);
          $cookies.put('userId', response.data._id);
          $state.go('home');
        })
      ;
    },
    login: function(user) {
      return $http
        .post('/login', user)
        .then(function(response) {
          angular.copy(response.data, $rootScope.user);
          $cookies.put('userId', response.data._id);
          $state.go('home');
        })
      ;
    },
    logout: function() {
      $http
        .get('/logout')
        .then(function() {
          angular.copy({}, $rootScope.user);
          $cookies.remove('userId');
          $state.go('home');
        })
        .catch(function() {
          console.log('Problem logging out.');
        })
      ;
    },
    getCurrentUser: function() {
      // user is logged in
      if (Object.keys($rootScope.user).length > 0) {
        return $q.when($rootScope.user);
      }
      // user is logged in, but page has been refreshed and $rootScope.user is lost
      if ($cookies.get('userId')) {
        return $http.get('/current-user')
          .then(function(response) {
            angular.copy(response.data, $rootScope.user);
            return $rootScope.user;
          })
        ;
      }
      // user isn't logged in
      else  {
        return $q.when({});
      }
    }
  };
}
Run Code Online (Sandbox Code Playgroud)

编辑 - 尝试失败+尝试成功:

beforeEach(module('auth'));
beforeEach(inject(function(_Auth_) {
  Auth = _Auth_;
  spyOn(Auth, 'requestCurrentUser');
}));
beforeEach(module('mean-starter', 'ngCookies', 'templates'));
beforeEach(inject(function(_Auth_, _$httpBackend_, _$rootScope_, _$cookies_, _$q_) {
  // Auth = _Auth_;
  $httpBackend = _$httpBackend_;
  $rootScope = _$rootScope_;
  $cookies = _$cookies_;
  $q = _$q_;
}));
// beforeEach(function() {
//   spyOn(Auth, 'getCurrentUser');
// });
afterEach(function() {
  expect(Auth.getCurrentUser).toHaveBeenCalled();
  $httpBackend.verifyNoOutstandingExpectation();
  $httpBackend.verifyNoOutstandingRequest();
});
Run Code Online (Sandbox Code Playgroud)

我不确定为什么这不起作用(独立于使用inject两次的问题).

我试图绕过必须使用$provide,因为我最初觉得hacky /怪异.在考虑了一些之后,我现在感觉$provide很好,并且根据你的建议使用mock-auth是太棒了!两者都适合我.

auth.factory.spec.js我刚加载auth模块(我正在调用它auth,而不是mean-auth加载)mean-starter.这没有run块问题,因为该模块没有run块代码,但它允许我测试我的Auth工厂.在其他地方,这有效:

beforeEach(module('mean-starter', 'templates', function($provide) {
  $provide.value('Auth', {
    requestCurrentUser: jasmine.createSpy()
  });
}));
Run Code Online (Sandbox Code Playgroud)

和梦幻般的mock-auth解决方案一样:

auth.factory.mock.js

angular
  .module('mock-auth', [])
  .factory('Auth', Auth)
;

function Auth() {
  return {
    requestCurrentUser: jasmine.createSpy()
  };
}
Run Code Online (Sandbox Code Playgroud)

user.service.spec.js

beforeEach(module('mean-starter', 'mock-auth', 'templates'));
Run Code Online (Sandbox Code Playgroud)

sca*_*rlz 6

我的理解是,当您在Angular单元测试中加载模块时,会调用运行块.

正确.

我认为如果你正在测试一个组件,你不会想要同时测试运行块,因为单元测试应该只测试一个单元.真的吗?

同样正确,现在你正在有效地测试Auth和运行块的集成,并且没有一个与另一个隔离.

如果是这样,有没有办法阻止运行块运行?我的研究让我认为答案是"不",并且运行块总是在加载模块时运行,但也许有一种方法可以覆盖它.如果没有,我将如何测试运行块?

实现后,不能阻止运行块运行.但是,通过一些小的重构仍然可能,因为您的问题最终是模块化的问题.无法看到您的模块声明,我想它看起来像这样:

angular.module('mean-starter', ['ngCookies'])

  .factory('Auth', function($cookies) {
    ...
  });

  .run(function(Auth, $rootScope) {
    ...
  });
Run Code Online (Sandbox Code Playgroud)

此模式可以分解为模块以支持可测试性(和模块可重用性):

angular.module('mean-auth', ['ngCookies'])

  .factory('Auth', function() {
    ...
  });

angular.module('mean-starter', ['mean-auth'])

  .run(function(Auth, $rootScope) {
    ...
  });
Run Code Online (Sandbox Code Playgroud)

现在,您可以Auth通过mean-auth仅将模块加载到其测试中来单独测试工厂.

虽然这解决了运行块干扰您的单元测试Auth的问题,但您仍然面临模拟问题,Auth.getCurrentUser以便单独测试运行块.您引用的博客文章是正确的,因为您应该利用模块的配置阶段来存根/监视运行阶段使用的依赖项.因此,在你的测试中:

module('mean-starter', function ($provide) {
  $provide.value('Auth', {
    getCurrentUser: jasmine.createSpy()
  });
});
Run Code Online (Sandbox Code Playgroud)

至于你的最后一个问题,你可以通过将它们声明为模块来创建可重用的模拟.例如,如果要创建可重用的模拟工厂,Auth请在单元测试之前加载的单独文件中定义它:

angular.module('mock-auth', [])

 .factory('Auth', function() {
   return {
     getCurrentUser: jasmine.createSpy()
   };
 });
Run Code Online (Sandbox Code Playgroud)

然后在您需要它的任何模块之后的测试中加载它,因为angular将覆盖具有相同名称的任何服务:

module('mean-starter', 'mock-auth');
Run Code Online (Sandbox Code Playgroud)