Search code examples
angularinputuploadcypressantd

Upload file in Cypress without input[type="file"] showing in DOM


I am doing e2e testing on an Angular project with Ant design (NG-ZORRO). I have a button nz-button which on click opens the file explorer just like an would do. On my modal component code, I have a <input #file type="file" (change)="import($event.target)" />. It does not appear at all either in the DOM, in the UI or in Devtool. It is triggered by an IMPORT button (which appears) in the footer that has a (click)="file.click()" property.

I want to use the .selectFile() method from Cypress in order to import a file through that IMPORT button, but the command : cy.get(.import-button).selectFile('file.csv') won't work because my button is not an <input type="file"> ; and if I try to use cy.get(input[type=file]) instead, Cypress does not find it, as it does not appear on Devtool.

Do you have an idea of why and/or may I test file uploading with Cypress in that case ?

I searched for an answer for many hours and still could not figure it out


Solution

  • You probably want to add the {action:'drag-drop'} option to the selectFile command.

    Setting the action to drag-drop changes the behavior of the command to instead mimic a user dragging files from the operating system into the browser, and dropping them over the selected subject. In this mode, the subject can be any DOM element or the document as a whole.

    cy.get(.import-button).selectFile('file.csv', {action:'drag-drop'})
    

    From your description, I would say that the <input> used to fire the action is added on the fly by the application, which means it's going to be very hard to use it directly in the test.