1

I am trying to test a http request with dynamic url

I have something in my service file like

My service file.

//other service codes..
//other service codes..
var id = $cookies.id;
return $http.get('/api/product/' + id + '/description')
//id is dynamic 

Test file

describe('test', function () {
    beforeEach(module('myApp'));

    var $httpBackend, testCtrl, scope;

    beforeEach(inject(function (_$controller_, _$httpBackend_, _$rootScope_) {
        scope = _$rootScope_.$new();
        $httpBackend = _$httpBackend_;
        testCtrl = _$controller_('testCtrl', {
            $scope: scope
        });
    }));

    it('should check the request', function() {
        $httpBackend.expectGET('/api/product/12345/description').respond({name:'test'});
        $httpBackend.flush();
        expect(scope.product).toBeDefined();
    })
});

I am getting an error saying

Error: Unexpected request: GET /api/product/description

I am not sure how to test the dynamic url. Can anyone help me about it? Thanks a lot!

1 Answer 1

2

You don't have id set in your code, so the url becomes:

/api/product//description

Which is reduced to what you see in the unexpected request (// -> /)

So, why isn't id defined? Show the code where you set it.

In testing 'dynamic' urls, you need to set up your test so that you know what the value of id is, and expect that. There isn't a way to expect patterns of urls.

You can modify the value of cookies by changing the first line of your describe block:

beforeEach(module('myApp', function($provide) {
  $provide.value('$cookies', {
    id: 3
  });
}));

Now you can expect that id will be three when the URL call happens.

This is pretty crude though. You could also just inject $cookies in the second beforeEach block and set it

beforeEach(inject(function($cookies) {
    $cookies.put('id', 3);
}))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.