2016-10-26 35 views
1

我有一种方法可以根据请求的资产类型动态设置$ http请求的responseType属性。我想单元测试使用Jasmine设置正确的响应类型。如何在AngularJS中对responseType进行单元测试

从我发现的情况,你可以期待一个带有某些标题的请求,但responseType不是一个标题,它是请求配置的一部分。这里是我的代码示例(在TypeScript中)。

let config = { 
 
    headers: { 
 
    'Content-Type': contentType 
 
    } 
 
} 
 
if (contentType.startsWith('image')) { 
 
    config.responseType = 'arraybuffer'; 
 
} 
 
$http.get(url, config);

回答

1

好吧,这是有点晚了,我已经花了相当这一段时间,但我终于得到了这个工作。

假设你正在重建一个beforeEach钩子中的$ httpBackend(我的将它分配给一个名为'backend'的变量......在App配置中(或者是一个更全局的beforeEach钩子,还没有尝试过这种方式),你需要一个装饰功能添加到$ httpBackend服务:

app.decorator('$httpBackend', ['$delegate', function ($delegate) { 

$delegate.interceptedCalls = []; 
var $httpBackend = function (method, url, data, callback, headers, timeout, withCredentials, responseType, 
             eventHandlers, uploadEventHandlers) { 
    $delegate.interceptedCalls.push({ 
     method: method, 
     url: url, 
     timestamp: new Date(), 
     type : responseType 
    }); 
    return $delegate.apply(null, arguments); 
}; 
    angular.extend($httpBackend, $delegate); 
    return $httpBackend; 
}]); 

所有这一切确实是增加一个interceptedCalls属性后端的对象将包含所有通过它去请求的列表。

然后,在您的测试文件中,您可以这样做:

it("forwards the data correctly",function(){ 
     var headers = { 
      'Content-Type' : 'application/json', 
      'Accept': 'application/json, text/plain, */*' 
     }; 

     backend.expectPOST('/someRoute/',{"A" : "B"},headers) 
      .respond(200,"dsfkjlasdfasdfklsdfd"); 

     service.functionThatCallsSomeRoute({"A" : "B"}); 
     backend.flush(); 

     expect(backend.interceptedCalls[0]['type']).to.equal('arraybuffer'); 
}); 

可能不是最好的方法,但由于我基本上在每次测试之前刷新整个事件(后端和服务测试),它将在对象上有所有调用。

相关问题