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

Daa*_*aan 1 unit-testing http angularjs 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) {
      });
    }
Run Code Online (Sandbox Code Playgroud)

测试:

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);
Run Code Online (Sandbox Code Playgroud)

它通常在我将测试中的$ rootScope设置为某个值时起作用,但在此测试中则不行.

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

gka*_*pak 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属性,你的服务将会使用$rootScope,它对此一无所知config.


解决方案:

为了将config属性添加到实际$rootScope更改您的代码,如下所示:

$rootScope.config = { apiUrl: 'foo' };
Run Code Online (Sandbox Code Playgroud)