简体   繁体   中英

Angular testing http request error

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!

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);
}))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM