使用$ httpBackend服务进行AngularJS单元测试。出于某种原因,$httpBackend.expectGET('')
或$httpBackend.expectGET()
似乎对来自测试代码的请求起了全面作用,即Karma说测试通过SUCCESS。
更准确地说,如果我用:
模拟后端$httpBackend.expectGET('').respond(200,'all good');
进行$http.get('specific/url/here')
调用的测试角度代码将被这个空的$ $ httpBackend.expectGET('')捕获。
我知道这是抓住请求的那个,因为如果我用:
来模拟后端$httpBackend.expectGET('bad/url/here').respond(200,'all good');
然后Karma FAILs留言:
Error: Unexpected request: GET specific/url/here
Expected GET bad/url/here
这是预期的行为吗?
我没有看到相关内容in the docs。
更新
注意到一些非常奇怪的东西。如果expectGET()传递了url
参数,则没有任何区别。重要的是声明$httpBackend.expectGET()
的顺序,它必须与请求从应用程序代码进入的顺序相同。
例如,如果模拟的请求是:
$httpBackend
.expectGET(URL_A)
.respond({
teams: [{
team_id: 6,
team_name: 'foo'
}]
});
$httpBackend
.expectGET(URL_B)
.respond({
data: [{
data_id: 1
}]
});
请求从应用程序到达的顺序首先是URL_A,然后是URL_B,无论我们是否明确指定URL,测试都会通过。
但是如果我们改变模拟请求的顺序,那么测试就会失败。
我再次没有看到这一点in the docs。