[英]unit testing file upload in angular
I am using the nf-file-upload module to upload a file to my backend. 我正在使用nf-file-upload模块将文件上传到后端。 The code for the file upload is as follows:
文件上传的代码如下:
$scope.upload = function (file) {
console.log(file)
Upload.upload({
url: 'http://localhost:3000/fileupload',
data: {file: file[0]},
}).then(function (resp) {
console.log('Success ' + resp.config.data.file.name + ' uploaded. Response: ' + resp.data);
}
The file uploading works great. 文件上传效果很好。 however, when I create my unit test:
但是,当我创建单元测试时:
it('should send file to backend for processing', function(){
var mockFile = {file:[{"name":"file.bin", "size":1018, "type":"application/binary"}]};
httpBackend.when('POST', 'http://localhost:3000/fileupload').respond(200, {"filePath":"http://localhost:3000/uploads/file.txt"});
scope.upload(mockFile);
httpBackend.flush();
});
I get an error: 我收到一个错误:
TypeError: undefined is not an object (evaluating 'resp.config.data.file.name')
What am I doing wrong? 我究竟做错了什么?
The then
method using the resp
argument. then
使用resp
参数的方法。 In the normal conditions, you'll receive a object that have the structure: { config:{ data: { file:{ name: 'a name'} } } } 在正常情况下,您会收到一个具有以下结构的对象:{config:{data:{file:{name:'a name'}}}}
but in your test you don't respond with the same structure. 但是在测试中,您不会以相同的结构进行响应。
EDIT: Ok. 编辑:好的。 I got this.
我懂了。 the way that ng-file-uploader returns the data it's not mockable.
ng-file-uploader返回数据的方式是不可模拟的。 You don't get the name of the file in the resp.data.config.file.name, Instead, saves the filename in a variable before upload the file.
您不会在resp.data.config.file.name中获得文件名,而是在上传文件之前将文件名保存在变量中。 Like this:
像这样:
$scope.upload = function (file) {
var fileName = file.name;
Upload.upload({
url: 'http://localhost:3000/fileupload',
data: {file: file[0]},
})
.then(function (resp) {
console.log('Success ' + fileName + ' uploaded. Response: ' + resp.data);
});
};
Check this codepen codepen.io/gpincheiraa/pen/MyrvQK Good luck! 检查此codepen codepen.io/gpincheiraa/pen/MyrvQK祝您好运!
You need to run a digest cycle. 您需要运行一个摘要循环。
it('should send file to backend for processing', function(){
var mockFile = {file:[{"name":"file.bin", "size":1018, "type":"application/binary"}]};
httpBackend.when('POST', 'http://localhost:3000/fileupload').respond(200, {"filePath":"http://localhost:3000/uploads/file.txt"});
scope.upload(mockFile);
httpBackend.flush();
scope.$digest();
});
This will resolve the promise and trigger the return data. 这将解决承诺并触发返回数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.