簡體   English   中英

在我的情況下如何為HTTP請求創建單元測試

[英]How to create unit test for http request in my case

我正在嘗試為隨機生成的URL創建單元測試。

我的項目Controller JS

init()

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

我的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
}

單元測試:

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

該應用程序有效,但我正在

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

當我運行單元測試時,因為我的URL中將包含隨機數。

我不確定如何模擬網址,因為它是隨機生成的。 有人可以幫我嗎? 非常感謝!

你有沒有嘗試過這樣的事情,

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

$ httpBackend.when()方法確實支持正則表達式。

如果是動態環境變量,

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM