How to provide mock files to change event of <input type='file'> for unit testing

前端 未结 4 429
死守一世寂寞
死守一世寂寞 2021-01-03 21:21

I\'m having difficulties with a unit test in which I want to verify the processing of a file, which would usually be selected in the view via

4条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-03 21:31

    UPDATE: Thanks to @PeteBD,

    Since angularjs version 1.2.22, the jqLite are now support passing a custom event object to triggerHandler(). See: d262378b


    If you are using only jqLite,

    the triggerHandler() will never work as it will pass a dummy event object to handlers.

    The dummy event object look like this (copied from jqLite.js#L962)

    {
      preventDefault: noop,
      stopPropagation: noop
    }
    

    As you can see, it doesn't even have a target property.

    If you are using jQuery,

    you could trigger an event with a custom event object like this:

    input.triggerHandler({
      type: 'change',
      target: {
        files: fileList
      }
    });
    

    and the evt.target.files will be the fileList as you are expecting.

    Hope this helps.

提交回复
热议问题