When performing automated testing with Cypress, handling file uploads can be achieved through various methods. For uploading PDF files, the cypress-file-upload plugin is a widely used and practical solution specifically designed for file upload scenarios in Cypress.
Step 1: Install cypress-file-upload
First, install the cypress-file-upload plugin using npm:
bashnpm install --save-dev cypress-file-upload
Step 2: Import the plugin
Import the plugin into your Cypress test file or the commands.js file:
javascriptimport 'cypress-file-upload';
Step 3: Prepare the PDF file
Place the PDF file in the project's fixtures folder. Assume the file is named example.pdf.
Step 4: Write the test script
In your Cypress test script, use cy.fixture() and cy.get() together to upload the file. Example code:
javascriptdescribe('PDF File Upload Test', () => { it('should upload a PDF file', () => { cy.visit('http://example.com/upload'); // Replace with the actual upload page URL cy.fixture('example.pdf').then(fileContent => { cy.get('input[type="file"]').upload({ fileContent, fileName: 'example.pdf', mimeType: 'application/pdf' }, { uploadType: 'input' }); }); cy.get('#upload-button').click(); // Trigger the upload action }); });
In this test script:
cy.visit()navigates to the page containing the file upload functionality.cy.fixture()reads the PDF file located in thefixturesfolder.cy.get()selects the file input field and uploads the PDF file using the.upload()method.- After uploading,
cy.get()selects the upload button and clicks it to submit the file.
This approach effectively handles PDF file uploads in Cypress. By simulating user behavior in web applications, it ensures that the upload functionality operates as expected.