$ httpbackend.flush()抛出当前。$$ route.title未定义

时间:2016-04-04 15:05:03

标签: javascript angularjs unit-testing karma-runner httpbackend

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

boolean retval = DoubleStream.of(weeks).anyMatch(i->i==10.0);

这是单元测试,必须测试传递给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);
          });
        }
    };
});

不幸的是,当调用'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(); }); }); 函数时,测试抛出: TypeError: undefined is not an object (evaluating 'current.$$route.title') ,我不明白为什么......

完整堆栈跟踪:

httpBackend.flush()

1 个答案:

答案 0 :(得分:0)

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

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

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