2013-10-08 30 views
3

我对AngularJS相当陌生,并且正在努力学习一些最佳实践。我有事情的工作,但想开始添加一些单元测试到我的模块和控制器。我期待解决的第一个问题是我的AuthModule。angularJS单元测试哪里运行包含HTTP请求?

我有一个AuthModule。该模块注册一个名为“AuthModule”的工厂,并公开诸如“setAuthenticatedUser”之类的东西,以及诸如“isLoggedIn”和“currentUser”之类的字段。我认为这是AngularJS应用程序中相当常见的模式,在具体的实现细节上有一些变化。

authModule.factory( 'AuthModule', 功能(APIService,$ rootScope){

var _currentUser = null; 
    var _isLoggedIn = false; 

    return { 
    'setAuthenticatedUser' : function(currentUser) { 

     _currentUser = currentUser; 
     _isLoggedIn = currentUser == null ? false : true; 

     $rootScope.$broadcast('event:authenticatedUserChanged', 
      _currentUser); 

     if (_isLoggedIn == false) { 
     $rootScope.$broadcast('event:loginRequired') 
     } 

     $rootScope.authenticatedUser = _currentUser; 
     $rootScope.isLoggedIn = _isLoggedIn; 

    }, 
    'isLoggedIn' : _isLoggedIn, 
    'currentUser' : _currentUser 
    } 
}); 

模块做了一些其他的东西像注册一个事件的处理 “loginRequired” 的人发回主屏幕,这些事件是由AuthModule工厂提高。

authModule.run(function($rootScope, $log, $location) { 
    $rootScope.$on("event:loginRequired", function(event, data) { 
    $log.info("sending him home. Login is required"); 
    $location.path("/"); 
    }); 
}); 

最后,该模块具有将使用API​​服务,我要确定登录用户当前表单后面跑块结束。

authModule.run(
    function(APIService, $log, AuthModule) { 
     APIService.keepAlive().then(function(currentUser) { 
     AuthModule.setAuthenticatedUser(currentUser.user); 
     }, function(response) { 
     AuthModule.setAuthenticatedUser(null); 
     }); 
    }); 

下面是我的一些问题:

我的问题是这个你会如何设置测试?我会认为我需要模拟APIService?我很难过,因为我不断收到意外的POST请求给我的/ keepalive函数(在APIService.keepAlive()中调用)?

有什么办法可以使用$ httpBackend来返回正确的响应给实际的KeepAlive调用吗?这将阻止我不得不模拟API服务?

我是否应该将获取当前登录用户的.run()块拉出AuthModule并将其放入主应用程序中?看起来无论我把run()块放在哪里,我似乎都无法在加载模块之前初始化$ httpbackend?

AuthModule应该是自己的模块吗?还是应该使用主应用程序模块并在那里注册工厂?

回答

2

对于主要方法,运行块是Angular中最接近的东西。运行块是需要运行以启动应用程序的代码。在完成所有服务配置并创建喷油器后执行。运行块通常包含很难进行单元测试的代码,因此应该在隔离模块中声明,以便在单元测试中可以忽略它们。 angularjs docs

我建议你看看这个authentication service,使用服务是要走的路。

希望这会有所帮助...祝你好运