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?

Answers


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.


Need Your Help

LINQ error to select a column from the table

c# asp.net-mvc linq

I got the Error in "context" in Controller using LINQ when i try to get the "value" from JQuery for binding the IDs from 2 different tables based upon the user selection in the dropdownlist

Control which lines have points?

javascript chart.js

With Chart.js, you can set in the options of the graph to show points or not: