2

I would like to test my resource with following URL:

    $resource(API_URL+'items/:id', {});

Where API_URL equals /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);
    });
});

But the problem is that this test fails for some strange reason:

    Error: Unexpected request: GET modules/home/partials/home.html
    No more request expected
        at $httpBackend 

And when I add slash to $httpBackend URL like this:

    $httpBackend.expectGET(API_URL+'/items/1').respond({id:1});

It throws following expection:

    Error: Unexpected request: GET /app/api/items/1
    Expected GET /app/api//items/1
        at $httpBackend 

Note double slash in expected GET.

How to fix it?

Update: Code from 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;
    }]);

Update2: If I change httpBackend url like this (just add localhost and not adding slash before items):

      $httpBackend.expectGET('http://localhost:8080'+API_URL+'items/1').respond({id:1});

Then the error is:

    Error: Unexpected request: GET /app/api/items/1
    Expected GET http://localhost:8080/app/api/items/1
        at $httpBackend 

Update3: If I for example hard code that API_URL like this:

 var url = 'app/api/items/1';
        $httpBackend.expectGET(url).respond({id:1});

The error is:

 Error: Unexpected request: GET /app/api/items/1
    Expected GET app/api/items/1
        at $httpBackend

But when I add slash at the begining of url, then it requests home partial modules/home/partials/home.html as with API_URL.

    Error: Unexpected request: GET modules/home/partials/home.html
    No more request expected
        at $httpBackend 
Tw1sty
  • 373
  • 7
  • 16

1 Answers1

2

It turned out that the problem was with ui-router. Namely, the following configuration:

$urlRouterProvider.otherwise("/");

I just needed to eliminate this configuration in the tests:

beforeEach(module(function ($urlRouterProvider) {
    $urlRouterProvider.otherwise(function(){return false;});
}));

Found this solution on https://github.com/angular-ui/ui-router/issues/212

Tw1sty
  • 373
  • 7
  • 16