2016-01-22 59 views
2

如何測試這種類型的http格式?角單元測試:錯誤:意外的請求:GET

$http({ 
    method: 'GET', 
    url: 'https://api.github.com/user/repos', 
    headers:{ 
     'Authorization': "Basic " + btoa("xxxx:xxxx"), 
     'Accept': 'application/json; odata=verbose' 
    } 
}) 
.success(function(data, status, headers, config) { 
    $scope.valid = true; 
    $scope.collection = data; 
}) 
.error(function(data, status, headers, config) { 
    $scope.error = data; 
}); 

測試代碼,

it('should demonstrate using when (200 status)', inject(function($http, $httpBackend) { 

    var $scope = {}; 

    /* Code Under Test */ 
    $http({ 
     method: 'GET', 
     url: 'https://api.github.com/user/repos', 
     headers:{ 
      'Authorization': "Basic " + btoa("xxxxx:xxxx"), 
      'Accept': 'application/json; odata=verbose' 
     } 
    }) 
    .success(function(data, status, headers, config) { 
     $scope.valid = true; 
     $scope.collection = data; 
    }) 
    .error(function(data, status, headers, config) { 
     $scope.error = data; 
    }); 
    /* End */ 

    $httpBackend 
    .when('GET', 'https://api.github.com/user/repos', undefined, { 
     Authorization: "Basic " + btoa("xxxxx:xxxx"), 
     Accept: "application/json;odata=verbose" 
    }) 
    .respond(200, { foo: 'bar' }); 

    $httpBackend.flush(); 

    expect($scope.valid).toBe(true); 
    expect($scope.collection).toEqual({ foo: 'bar' }); 

})); 

我得到這個錯誤,

Error: Unexpected request: GET https://api.github.com/user/repos No more request expected

任何想法?

+0

應該不是'。當( 'GET',「HTTPS:// api.github.com /用戶/ repos''是實際工作呼叫之前 – maurycy

+0

如何來了嗎?我下面前應定義本指南http://www.bradoncode.com/blog/2015/06/26/unit-testing-http-ngmock-fundamentals/ – laukok

+0

美中不足的'$ http'電話實際調用時,將'$ httpBackend'之前'$ HTTP()' – maurycy

回答

3

你可以試試這個

$httpBackend.whenGET('https://api.github.com/user/repos', undefined, { 
    Authorization: "Basic " + btoa("xxxxx:xxxx"), 
    Accept: "application/json;odata=verbose" 
}).respond(function(){ return [200,[{foo: 'bar' }]]}); 
+0

它工作的感謝!但是爲什麼呢?我不明白! – laukok

+1

@teelou,基本上$ httpbackend的respond方法可以採取兩個版本之一是1)函數返回一個狀態,數據和hea數組der信息等,第二個是包含狀態和數據等的靜態數據集。儘管在功能版本中狀態是強制性的。 – G1P

+0

非常感謝! :) – laukok