Reputation: 365
I am using the nf-file-upload module to upload a file to my backend. 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?
Upvotes: 0
Views: 7622
Reputation: 3623
The then
method using the resp
argument. In the normal conditions, you'll receive a object that have the structure:
{
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. 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. 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!
Upvotes: 2
Reputation: 6620
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.
Upvotes: 0