简体   繁体   中英

How to create unit test for http request in my case

I am trying to create a unit test for a random generate url.

My item Controller JS

init()

function init(){
   var results = itemService.request();    
   other codes..
}

My itemService js

function request(){
    other codes..
    return $http.get(url);
}

function generateUrl() {
    var url = 'https://project/'
    var num = Math.floor((Math.random() * 100) + 1);
    url += num;
    other codes to generate more attribute for url…

    return url
}

Unit test:

beforeEach(function () {
        module(‘itemApp’);

        inject(function ($injector) {
            $controller = $injector.get('$controller');
            itemService = $injector.get(‘itemService’);
            $rootScope = $injector.get('$rootScope');
            $scope = $rootScope.$new();
            $httpBackend = $injector.get('$httpBackend');
        });

        vm.$controller(‘itemCtrl’, {
            ‘$scope’:$scope
        })

     $httpBackend.when('GET', 'https://project/15/other-attributes').respond(200);
});

 describe('initialization', function() {      
       it(‘start init’ , function(){
            //not sure what to do.
       });

The application works but I am getting

Error: Unexpected request: GET https://project/12/other-attributes

when I ran the unit test because I will have random numbers in my url.

I am not sure how to mock the url because it generates randomly. Can anyone help me about it? Thanks a lot!

Have you tried something like this,

$httpBackend.when('GET', /https:\/\/project\/[0-9]+\/other-attributes/).respond(200);

$httpBackend.when() method does support regex.

In case of dynamic environment variables,

var environmentUrl = "http://google.com";
$httpBackend.when('GET', new RegExp(environmentUrl + '/[0-9]+/other-attributes')).respond(200);

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