gpt4 book ai didi

angularjs - 使用 Jasmine 测试 AngularJS 资源

转载 作者:行者123 更新时间:2023-11-28 20:08:29 27 4
gpt4 key购买 nike

我想使用以下 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(只需添加本地主机而不是在项目前添加斜杠):

      $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

最佳答案

原来是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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com