How to simulate a file upload during tests?

25 views Asked by At

I have a Stencil component which allows to upload a file:

@Component({
  tag: 'app-file-import',
  styleUrl: 'file-import.css',
  shadow: true
})
export class AppFileImport {
  importFile(event: any): void {
    const files: File[] = event.target?.files || [];
    const uploadedFile = files[0];

    //logic stuff
  }

  render() {
    return (
      <div>
        <label htmlFor="file">upload a file</label>
        <input type="file" onInput={this.importFile} name="file" id="file" />
      </div>
    );
  }
}

And I would like to write a test that simulates a file upload. I have a PDF example in my project and I would like to use it in my tests:

describe('testing file import component', () => {
   let page: SpecPage;
   let host: HTMLElement;

   beforeEach(async () => {
       page = await newSpecPage({
           components: [AppFileImport],
           html: '<app-file-import></app-file-import>'
       });

       host = page.body.querySelector('app-file-import');
   });

   it('should import the file', async () => {
       const file = await fetch("./example.pdf").then(response => response.blob());
       const input = host.shadowRoot.querySelector('input');
       input.value = file;
       input.dispatchEvent(new Event('input'));

       //test stuff
   });
});

But the fetch is not morking (InvalidURLException). Do you have any idea of how to do that?

0

There are 0 answers