$httpbackend.flush() 抛出电流。$$route.title 未定义

$httpbackend.flush() throws current.$$route.title is undefined

我尝试对发出 post 请求的简单工厂进行单元测试:

'use strict';

angular.module('app').factory('UserFactory', function ($http, $rootScope, $location) {
    return {
        'addUser': function (user) {
          $http.post('/api/user',
          {
            'user': user,
            'url': $location.path(),
            'title': $rootScope.title
          }).then(function(result){
            console.log(result);
          }).catch(function(err){
            console.log(err);
          });
        }
    };
});

这是单元测试,它必须测试传递给 Post 请求的主体:

'use strict';

describe('UserFactory', function() {
  var factory;
  var httpBackend;
  var rootScope;
  var location;

  beforeEach(module('app'));

  beforeEach(inject(function($injector, $httpBackend, $rootScope, $location) {
    httpBackend = $httpBackend;
    rootScope = $rootScope;
    location = $location;
    factory = $injector.get('UserFactory');
    rootScope.title = 'Home';
    spyOn(location, 'path').and.callFake(function(param) {
     if(param) {
       return location;
     } else {
       return '/home';
     }
    });
  }));

  it('should correctly call the url /api/user with all informations provided in the body', function() {
    httpBackend.when('POST', '/api/user')
      .respond(200);
    httpBackend.expectPOST('/api/user', {'user': 'user test', 'url': '/home', 'title': 'Home'});
    factory.addUser({name: 'user test'});
    httpBackend.flush();
    httpBackend.verifyNoOutstandingExpectation();
    httpBackend.verifyNoOutstandingRequest();
  });
});

不幸的是,当调用httpBackend.flush()函数时,测试抛出:TypeError: undefined is not an object (evaluating 'current.$$route.title'),我不明白为什么...

完整堆栈跟踪:

TypeError: undefined is not an object (evaluating 'current.$$route.title') in C:/front/app/scripts/app.js (line 9)
        C:/front/app/scripts/app.js:9:14402
        $broadcast@C:/front/bower_components/angular/angular.js:17348:33
        C:/front/bower_components/angular-route/angular-route.js:647:36
        processQueue@C:/front/bower_components/angular/angular.js:15757:30
        C:/front/bower_components/angular/angular.js:15773:39
        $eval@C:/front/bower_components/angular/angular.js:17025:28
        $digest@C:/front/bower_components/angular/angular.js:16841:36
        flush@C:/front/bower_components/angular-mocks/angular-mocks.js:1779:45
        C:/front/test/unit/factories/user-factory-spec.js:86:22

我发现问题来自位置模拟:

spyOn(location, 'path').and.callFake(function(param) {
     if(param) {
       return location;
     } else {
       return '/home';
     }
    });

我的 routeProvider 配置中没有名为 /home 的路由,因此它失败了。将其替换为 /,现在可以正常使用了。