使用$ rootScope和$ httpBackend进行Angularjs单元测试

时间:2014-01-14 14:51:20

标签: unit-testing angularjs http httpbackend

我有一个触发HTTP请求的服务。此请求使用$ rootScope.config对象(存储了我的基本URL),但由于某些原因,当我使用$ httpBackend时,$ rootScope未正确加载。

服务:

myAppServices.factory('Auth', function($rootScope, $http, $cookieStore){   
  return {
    logout: function(success, error) {
      $http.get($rootScope.config.apiUrl + '/users/logout').then(function(response){
      }, function(response) {
      });
    }

测试:

describe('services', function() {
  var Auth;
  var $httpBackend;
  var $cookieStore;
  var $rootScope;

  beforeEach(function() {
    module('myApp.services');
  });

  beforeEach(inject(function($injector) {
    $httpBackend = $injector.get('$httpBackend');
    $cookieStore = $injector.get('$cookieStore');
    $rootScope = $injector.get('$rootScope');
    Helper = $injector.get('Helper');
    Auth = $injector.get('Auth');
  }));

  afterEach(function() {
    $httpBackend.verifyNoOutstandingExpectation();
    $httpBackend.verifyNoOutstandingRequest();
  });

describe('logout', function() {
  it('should make a request and invoke callback', function() {
    // I try to set $rootScope here, works in my other tests, but not in this test
    $rootScope = { config: { apiUrl: 'foo' } };

    var invoked = false;
    var success = function() {
      invoked = true;
    };
    var error = function() {};

    $httpBackend.expectPOST('/logout').respond();
    Auth.logout(success, error);
    $httpBackend.flush();
    $rootScope = { config: { apiUrl: 'foo' } };
    expect(invoked).toEqual(true);

当我在测试中将$ rootScope设置为某个值时,它通常有效,但在此测试中则不行。

为什么使用$ httpBackend时$ rootScope在我的服务中没有config属性?

1 个答案:

答案 0 :(得分:5)

问题:

有两个同名的东西引起混淆:

  • $rootScope(实际的$rootScope是所有Scope的祖先,并通过Angular的依赖注入注入。)
  • 您在测试套件中声明了一个名为$rootScope的局部变量。

为了清楚起见,我将后者称为$rootScope{var}


以下是发生的事情:

  1. 在某些时候,$rootScope会被注入您服务的构造函数中(稍后在发出$http请求时使用)。

  2. $rootScope{var}初始化为$injector.get('$rootScope');返回的值 此时$rootScope$rootScope{var}相同的对象。

  3. 此行:$rootScope = { config: { apiUrl: 'foo' } };创建对象,并将其指定为$rootScope{var}的值。
    此时$rootScope$rootScope{var} 不再相同的对象。

  4. $rootScope{var}确实有config属性,您的服务将使用$rootScopeconfigconfig一无所知


  5. 解决方案:

    要将$rootScope属性添加到实际的$rootScope.config = { apiUrl: 'foo' }; ,请更改您的代码:

    {{1}}