如何在AngularJS中对responseType进行单元测试

时间:2016-10-26 14:48:22

标签: angularjs unit-testing

我有一个方法可以根据被请求的资产类型动态设置$ http请求的responseType属性。我想使用Jasmine进行单元测试,确定正确的响应类型。

根据我的发现,您可以预期带有某些标头的请求,但responseType不是标头,它是请求配置的一部分。以下是我的代码示例(在TypeScript中)。



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




1 个答案:

答案 0 :(得分:1)

好的,这有点晚了,我已经花了很长时间,但我终于得到了这个。

假设你在beforeEach钩子中重建$ httpBackend(我将它分配给一个名为'后端的变量' ...在App配置中(或者更全球化) beforeEach hook,没有尝试过这种方式),你需要在$ 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');
 });

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