Unit test for input type = file


#1

i have a component, it has a form control --> input[type=file]. Now, i need write unit test for the action, the action method in component is:

addFile(e) {
  set(this, 'file', e.target.files[0]);
  this._checkFileSize(e.target.files[0]);
  const fileSizeAvailable = get(this, 'fileSizeAvailable');

  if (!fileSizeAvailable) {
    set(this, 'ifEditing', false);
    set(this, 'errorMessage', get(this, 'i18n').t('individual.new.attachFile_file_size_error'));
    return;
  }
  this._checkFileType(e.target.files[0]);
  const fileTypeAvailable = get(this, 'fileTypeAvailable');

  if (!fileTypeAvailable) {
    set(this, 'ifEditing', false);
    set(this, 'errorMessage', get(this, 'i18n').t('individual.new.attachFile_file_type_error'));
    return;
  }
  set(this, 'errorMessage', null);
  set(this, 'attachFileData.fileName', e.target.files[0].name);
}

the action ‘addFile’ is trigger by ‘change’ event.

testing framework which i used is ‘ember-mocha’.

Does anybody has the experience for it?

the testing code that i have written down is:

describe(‘Unit | Component | attachfile organization’, () => { setupComponentTest(‘attachfile-organization’, { needs: [], unit: true }); it(‘should add the file meta data if user upload a file’, function () { const component = this.subject({ file: {}, fileSizeAvailable: true, fileTypeAvailable: true });

component.send('addFile', {
  target: {
    files: [
      {
        lastModified: 1500514945000,
        lastModifiedDate: 'Thu Jul 20 2017 09:42:25 GMT+0800 (CST)',
        name: 'hahaa.docx',
        size: 223678
      }
    ]
  }
});
expect(component.get('file')).to.be.ok;

});});


#2

does the testing code is right?? it is seemed to be nothing for the code coverage on ‘addFile’


#3

Any time you invoke send, it operates asynchronously. In our test suites, we usually run the assertion later by calling Ember.run.next or Ember.run.later. You could try wrapping the last assertion in an Ember.run.next. In your test, you could also try invoking the addFile action manually like so:

component.actions.addFile.call(component, {
  target: {
    files: [
      {
        lastModified: 1500514945000,
        lastModifiedDate: 'Thu Jul 20 2017 09:42:25 GMT+0800 (CST)',
        name: 'hahaa.docx',
        size: 223678
      }
    ]
  }
});

Calling the action directly like this works around any asynchrony introduced by the send method.


#4

I should also point out that using send or Ember.run within a mocha test suite requires you to use the done callback or return a promise in the test case.


#5

many thanks for your explanation, I used component.send( ). your answer is also precious for me