我想使用以下 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 部分模块/home/partials/home.html。
Error: Unexpected request: GET modules/home/partials/home.html
No more request expected
at $httpBackend
最佳答案
结果发现问题出在 ui-router 上。即如下配置:
$urlRouterProvider.otherwise("/");
我只需要在测试中消除此配置:
beforeEach(module(function ($urlRouterProvider) {
$urlRouterProvider.otherwise(function(){return false;});
}));
在https://github.com/angular-ui/ui-router/issues/212上找到了这个解决方案
关于angularjs - 使用 Jasmine 测试 AngularJS 资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29731146/