简体   繁体   中英

unit testing file upload in angular

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?

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM