htmlcypressprimengcypress-file-upload

Can you get a Cypress test to do a file upload for a p-fileUpload?


I have an app that makes use of a p-fileUpload that I'm writing a Cypress test for.

I thought maybe I could do this using the selectFile method - but that hasn't worked.

Here is my p-fileUpload implementation in the html:

<p-fileUpload
    name="files"
    [url]="url"
    accept="text/xml"
    [multiple]="true"
    (onBeforeUpload)="onBeforeUpload($event)"
    (onUpload)="onUpload($event.files, $event.originalEvent.body)"
    (onError)="onError($event.files, $event.originalEvent ? $event.originalEvent.body : $event.error)"
    [attr.data-cy]="'fileUpload'"
  ></p-fileUpload>

And here is my attempt to upload a file in my Cypress test:

cy.get('[data-cy="fileUpload"]').should('be.visible')
        .then($upload => {

            cy.get('[data-cy="fileUpload"]').selectFile('cypress/fixtures/myfile.xlsx');

});

and here's the error I get:

cy.selectFile() can only be called on an <input type="file"> or a <label for="fileInput"> pointing to or containing a file input, but received the element:
<p-fileupload _ngcontent-dan-c234="" name="files" accept="text/xml" class="p-element" ng-reflect-name="files" ng-reflect-accept="text/xml" ng-reflect-url="transaction/api/v2/upload/xml?" ng-reflect-multiple="true" data-cy="fileUpload">...</p-fileupload>

Any suggestions?

Thanks much.


Solution

  • Try with the drag-drop option.

    cy.get('[data-cy="fileUpload"]')
      .selectFile('cypress/fixtures/myfile.xlsx', {action: 'drag-drop'})
    

    When you use this option Cypress searches within child elements of <p-fileUpload> for the <input> to which it will attach the file.

    Inspecting the HTML in dev-tools/Elements tab you should be able to find an <input> underneath the main element, for example (omitting some attributes)

    <p-fileupload>
      <div class="p-fileupload">
        <div class=" p-fileupload-buttonbar">
          <span class="p-button">
            <input type="file" />