如何测试模块的运行块

Esa*_*ola 3 angularjs

我希望我的AngularJS应用程序发出http请求以从服务器检索用户信息或重定向到登录屏幕.我在我的应用程序主模块的运行块中实现了它.但是如何在运行块中测试代码呢?或者我应该在控制器中移动此初始化代码以使其可测试?我正在用Karma和Jasmine写我的测试.

任何帮助,将不胜感激!

ama*_*rov 12

您可以通过模块的_runBlocks属性获取对运行块的引用.

包含模块代码的文件:

angular.module('xmpl', []).
  run(function() {
    // some code here
  });
Run Code Online (Sandbox Code Playgroud)

测试套件:

var myModule = angular.module('xmpl'),
    runBlock = myModule._runBlocks[0];
// Now can test the runBlock function according to your scenario
Run Code Online (Sandbox Code Playgroud)


Esa*_*ola 8

一种解决方案是将运行块中的代码移动到服务中:

angular.module('app', [])
  .run(function(runBlockService) {
    runBlockService.run();
  });
Run Code Online (Sandbox Code Playgroud)

并为该服务编写单元测试.