angularjs - 使用 Jasmine 测试 AngularJS 资源

标签 angularjs testing jasmine angular-ui-router angular-resource

我想使用以下 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/

相关文章:

angularjs - Angular 1.2 : ng-bind-html removes src attribute on img

javascript - 使用 Ajax 的 Angular.js 中的 2 个 Controller 和本地存储值之间存在竞争条件问题

java - 使用匹配器断言 Collection 包含 2 个具有相同属性的对象

unit-testing - 如何测试不太可能发生的并发场景?

javascript - 检查特定年龄

javascript - Jasmine ,$q 未定义

javascript - 使用 Angular.js/JavaScript 对两个数组值进行排序并按日期合并

ruby-on-rails - 为什么实例变量有时会在 RSpec 测试中被过度使用?

angularjs - 在 AngularJS 应用程序中运行 Karma 单元测试时出现 "Unexpected request"错误

javascript - 使用 Jasmine toEqual 未定义预期对象