【发布时间】:2015-04-19 14:25:26
【问题描述】:
我想使用以下 URL 测试我的资源:
$resource(API_URL+'items/:id', {});
其中 API_URL 等于 /app/api/
describe('item',function(){
it('should return same item id',function(){
$httpBackend.expectGET(API_URL+'items/1').respond({id:1});
var result = ItemService.item.get({id:1});
$httpBackend.flush();
expect(result.id).toEqual(1);
});
});
但问题是这个测试由于一些奇怪的原因失败了:
Error: Unexpected request: GET modules/home/partials/home.html
No more request expected
at $httpBackend
当我像这样向 $httpBackend URL 添加斜杠时:
$httpBackend.expectGET(API_URL+'/items/1').respond({id:1});
它引发以下期望:
Error: Unexpected request: GET /app/api/items/1
Expected GET /app/api//items/1
at $httpBackend
注意预期 GET 中的双斜杠。
如何解决?
更新: 来自 ItemService 的代码:
var itemService = angular.module("ItemServiceModule", []);
itemService.factory("ItemService", [ "$resource", "API_URL", function($resource,API_URL) {
var itemService = {
item: $resource(API_URL+'items/:id', {})
};
return itemService;
}]);
更新2: 如果我像这样更改 httpBackend url(只需添加 localhost 而不是在项目前添加斜杠):
$httpBackend.expectGET('http://localhost:8080'+API_URL+'items/1').respond({id:1});
那么错误是:
Error: Unexpected request: GET /app/api/items/1
Expected GET http://localhost:8080/app/api/items/1
at $httpBackend
更新3: 例如,如果我像这样对 API_URL 进行硬编码:
var url = 'app/api/items/1';
$httpBackend.expectGET(url).respond({id:1});
错误是:
Error: Unexpected request: GET /app/api/items/1
Expected GET app/api/items/1
at $httpBackend
但是当我在 url 的开头添加斜杠时,它会像 API_URL 一样请求 home partial modules/home/partials/home.html。
Error: Unexpected request: GET modules/home/partials/home.html
No more request expected
at $httpBackend
【问题讨论】:
-
显示
ItemService的代码 -
@Chandermani 好的,我添加了...
-
变量
API_URL是如何传递的 -
我很确定 API_URL 不是这个问题的原因。服务本身在应用程序中工作并正确注入到测试中(我使用 console.log 进行了测试)。否则我不会在异常消息中获得任何这些 url。
-
好的,第一个错误可能是由于其他一些测试。这是唯一正在运行的测试吗?
标签: angularjs testing jasmine angular-ui-router angular-resource