'Cypress selectFile fails with Blazor InputFile

I have a Blazor page for uploading a file; the Blazor code follows the example at https://docs.microsoft.com/en-us/aspnet/core/blazor/file-uploads?view=aspnetcore-6.0&pivots=server

For automated testing I am trying to use Cypress 9.4, in particular the new cy.selectFile method:

  cy.get('input[type="file"]').selectFile(
    {contents: 'foo.zip', 
     fileName: 'foo.zip', 
     mimeType: 'application/x-zip-compressed'}, 
    {force: true}
  );

I can wrap the code above in a cy.fixture or a cy.readFile; the result is the same.

The Cypress code triggers the OnChange on the Blazor component as expected, but when Blazor tries to read the file-stream an exception is thrown from the browser webassembly.

If I pretty-print the webassembly I get:

function p(e) {
    let t = -1;
    if (e instanceof ArrayBuffer && (e = new Uint8Array(e)),
    e instanceof Blob)
        t = e.size;
    else {
        if (!(e.buffer instanceof ArrayBuffer))
            throw new Error("Supplied value is not a typed array or blob.");
        if (void 0 === e.byteLength)
            throw new Error(`Cannot create a JSStreamReference from the value '${e}' as it doesn't have a byteLength.`);
        t = e.byteLength
    }

When uploading manually, then the code satisfies the first if-statement. When using Cypress.selectFile the exception 'Supplied value is not a typed array or blob' is thrown.

In both cases, 'e' is a File-object with the expected name and size; for some reason the Cypress code makes a File-object that is not an instance of ArrayBuffer.

Am I doing something wrong or is Blazor and Cypress still only just kind of playing together?



Solution 1:[1]

As of Cypress 9.5 (fix of issue 20003) selectFile works with Blazor.

The code below upload a zip. Setting the mime-type is probably not needed.

cy.readFile('foo.zip', null).then(
  (zip) => {
    cy.get('input[type="file"]').selectFile(
      { contents: zip, 
        fileName: 'foo.zip', 
        mimeType: 'application/x-zip-compressed'
      }, 
      {force: true}); 
    }
  );

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 clausc