Javascript 全局beforeach,用于使用Mocha和Angular模拟HTTP请求

Javascript 全局beforeach,用于使用Mocha和Angular模拟HTTP请求,javascript,angularjs,unit-testing,mocha.js,Javascript,Angularjs,Unit Testing,Mocha.js,我在模块中触发的请求很少。运行: angular.module('demo').run(function($http) { $http.get('/some/thing'); $http.get('/some/other/thing'); }); 当我在测试中使用$rootScope.$apply来解析模拟承诺时,我会得到'/some/thing'和'/some/other/thing'的意外请求错误 一种修复方法是在beforeach中设置$httpBackend: $httpBac

我在
模块中触发的请求很少。运行

angular.module('demo').run(function($http) {
  $http.get('/some/thing');
  $http.get('/some/other/thing');
});
当我在测试中使用
$rootScope.$apply
来解析模拟承诺时,我会得到
'/some/thing'
'/some/other/thing'
意外请求错误

一种修复方法是在beforeach中设置
$httpBackend

$httpBackend.when('GET', mockData.API_URL + '/some/thing').respond(200, {});
$httpBackend.when('GET', mockData.API_URL + '/some/other/thing').respond(200, {});
这将起作用,但这意味着我必须在使用
$rootScope.$apply
的每个测试文件之前将其放入其中

如何使那些
$httpBackend
为每个测试文件配置全局性?
或者有更好的解决方案吗?

来自“根级挂钩”:

您还可以选择任何文件并添加“根”级挂钩。例如 将beforeach()添加到所有descripe()块之外。这将导致 回调beforeach()以在任何测试用例之前运行,无论 它所在的文件(这是因为Mocha有一个隐藏的descripe() 块,称为“根套件”)

如果你在所有测试中都需要它,VinceOPS的答案是最好的。如果您不需要在每个测试中都使用它,我会做的就是将$httpBackend调用移动到一个单独的函数中,并将其放在一个共享的js文件中。然后,您只需在需要时从beforeach调用该函数

对于更复杂的配置,我通常为
descripe()
it()
或定义测试以防止编写(过多)重复代码的函数创建自己的包装函数

beforeEach(function() {   
    console.log('before every test in every file'); 
});