Angularjs $httpBackend.flush()在缓存GET请求时引发错误
我正在尝试测试我的服务是否使用缓存的GET请求 测试的简化版本:Angularjs $httpBackend.flush()在缓存GET请求时引发错误,angularjs,Angularjs,我正在尝试测试我的服务是否使用缓存的GET请求 测试的简化版本: var url = "/test"; var whenTestRequest = $httpBackend.when('GET', url); whenTestRequest.respond(200, "r1"); $http({ url: url, method: 'GET', cache: true }).success(function (value) { expect(value).toBe("r
var url = "/test";
var whenTestRequest = $httpBackend.when('GET', url);
whenTestRequest.respond(200, "r1");
$http({ url: url, method: 'GET', cache: true }).success(function (value) {
expect(value).toBe("r1");
});
$httpBackend.flush();
whenTestRequest.respond(200, "r2");
$http({ url: url, method: 'GET', cache: true }).success(function (value) {
expect(value).toBe("r1");
});
$httpBackend.flush();
我需要第二个$httpBackend.flush()
,以便调用第二个success
函数,但对flush的第二个调用抛出:
错误:没有挂起的刷新请求
因此,我需要在try
/catch
中包装flush
。这是可行的,但是否有正确的处理方法?我想我找到了一个解决方案-而不是调用$httpBackend.flush()
,而是调用$rootScope.$digest()
。这就是flush
在后台完成的操作,除了不检查是否有任何未决请求外,它还导致解决缓存满足的$http请求的承诺
当我切换一个项目,将指令模板存储在模板缓存中,而不是对每个模板执行http请求时,我遇到了这种情况。我以前的测试创建了如下指令:
beforeEach(inject(function($compile, $rootScope, $httpBackend) {
$httpBackend.expectGET('login.html').respond('<div></div>');
$compile('<login-page/>')($rootScope);
$httpBackend.flush();
}));
这允许每个
之前的运行,并且指令实际上已经生成,允许测试的其余部分正常继续。另一种方法是切换到使用$httpBackend.expectGET()
而不是$httpBackend.when()
。原因是“expect”版本更严格,您可以测试只发出一个HTTP请求。这种方法显著地改变了您的测试。坦白地说,我从来没有在测试中使用“when”函数b/c,我想断言HTTP请求是按照我期望的顺序/数量进行的。。。我们不可能是第一个碰到这件事的两个人,对吗?
beforeEach(inject(function($compile, $rootScope) {
$compile('<login-page/>')($rootScope);
$rootScope.$digest();
}));