全局BeforeEach,用于用Mocha和Angular模拟HTTP请求
Global BeforeEach for mocking HTTP request with Mocha and Angular
我有几个在module.run
中触发的请求:
angular.module('demo').run(function($http) {
$http.get('/some/thing');
$http.get('/some/other/thing');
});
当我在测试中使用$rootScope.$apply
来解决模拟承诺时,我得到'/some/thing'
和'/some/other/thing'
的unexpected request errors
。
$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
配置全局每个测试文件?
或者是否有更好的解决方案?
来自Mocha网站,在"根级钩子":
你也可以选择任何文件并添加"根"级钩子。例如,在所有的describe()块之外添加beforeEach()。这将导致回调到beforeEach(),在任何测试用例之前运行它所在的文件(这是因为Mocha有一个隐藏的description ()块,称为"根套件")。
beforeEach(function() {
console.log('before every test in every file');
});
如果你真的需要它在所有测试VinceOPS答案是最好的。我会做什么,如果你不需要它在每测试,但只是很多是移动$httpBackend调用到一个单独的函数,并把它放在一个共享的js文件。然后在需要的时候从beforeEach调用该函数。
对于更复杂的配置,我经常为describe()
, it()
或您定义测试的函数创建自己的包装器函数,以防止编写(太多)重复的代码。
相关文章:
- 用于单元测试的模拟Angular引导程序ui指令
- Angular js单元测试模拟文档
- 模拟Angular中的承诺:'那么'不开火
- Jasmine模拟Karma和Angular的链式方法
- Angular:模拟触摸设备上的鼠标离开
- Angular 添加模拟 JSON 数据
- 如何在angular的单元测试中模拟警报
- 如何模拟“angular.element”
- 全局BeforeEach,用于用Mocha和Angular模拟HTTP请求
- Angular单元测试,模拟使用$injector注入的服务
- 如何在不影响模板的情况下用angular模拟REST
- Angular、Jasmine会模拟整个模块的依赖关系.不可用!"错误
- 在Angular 2中模拟后端响应
- 如何注入在app.run函数中使用的模拟angular服务?
- 如何在模拟Angular服务中从JSON fixture中提取数据
- 如何模拟带参数的Angular服务方法
- 在Jasmine中对Angular进行单元测试时,将模拟自定义提供程序注入到提供程序中
- 如何用Jasmine在Angular应用程序中模拟d3.json()调用,用Karma任务运行器进行测试
- 你如何模拟 Angular 服务这是一个函数
- 在单元测试用例中模拟Angular $window