2014-11-17 115 views
1

我使用https://github.com/danialfarid/angular-file-upload为我的文件上传。它提供了一个称为progress的方法,当xhr请求收到progress事件时。这是从角文件上传的源代码:使用$httpBackend

xhr.upload.addEventListener('progress', function(e) { 
    deferred.notify(e); 
}, false); 

我的问题是现在,我应该怎么测试呢?我可以测试的成功和错误的方法与

$httpBackend.expectPOST("http://localhost:9001/").respond('ok'); 
$httpBackend.expectPOST("http://localhost:9001/").respond(500, 'some error'); 

,但我不能让许火的notify。有没有办法做到这一点?

编辑

,我想测试的一部分,是progress方法中:

$upload.http({url: url, method: 'POST', data: file}) 
    .progress(function(evt) { 

     // here is more code, that needs to be tested 

     self.$deferreds.upload.notify((100.0 * evt.loaded/evt.total).toFixed(2)); 
    }).success(function(data, status, headers, config) { 
     self.$deferreds.upload.resolve(data); 
    }).error(function(response) { 
     self.$deferreds.upload.reject(response); 
    }); 

回答

1

你想窥探$upload.http方法并返回一个模拟对象,让你注册进度,成功和错误回调。

spyOn($upload, 'http').andReturn({ 
    progress: function (progressCallback) { 
    this.progressCallback = progressCallback; 
    }, 
    success: function (errorCallback) { 
    this.errorCallback = errorCallback; 
    }, 
    error: function (errorCallback) { 
    this.errorCallback = errorCallback; 
    } 
}); 

然后你就可以在测试同步调用这些回调:

it('should do something', function() { 
    $upload.progressCallback(); 
    // or $upload.successCallback(); 
    // or $upload.errorCallback(); 

    expect('this').toBe('that'); 
}); 
0

我们正在谈论的单元测试?

为什么你需要测试第三方呢?

只是模拟这部分

也许我没有得到这个问题的想法,所以需要更多的测试应该覆盖的代码。

+0

我已经从我的应用程序添加更多的代码。我想测试当进度事件被触发时执行的代码。 – 23tux