0
0
Cypresstesting~15 mins

File upload (cy.selectFile) in Cypress - Build an Automation Script

Choose your learning style9 modes available
Upload a file using the file input and verify upload success message
Preconditions (2)
Step 1: Locate the file input element with id 'file-upload'
Step 2: Use the file selector to choose 'sample.txt' from fixtures
Step 3: Click the submit button with id 'upload-submit'
Step 4: Wait for the upload success message to appear with id 'upload-success'
✅ Expected Result: The upload success message displays text 'File uploaded successfully!'
Automation Requirements - Cypress
Assertions Needed:
Verify the file input contains the selected file
Verify the success message is visible and contains correct text
Best Practices:
Use cy.selectFile() to simulate file selection
Use data-cy or id selectors for stable element targeting
Use cy.get() with assertions for visibility and content
Avoid hardcoded waits; rely on Cypress automatic waits
Automated Solution
Cypress
describe('File Upload Test', () => {
  beforeEach(() => {
    cy.visit('/upload');
  });

  it('uploads a file and verifies success message', () => {
    // Select the file input and attach the file
    cy.get('#file-upload').selectFile('cypress/fixtures/sample.txt');

    // Verify the file input has the file selected
    cy.get('#file-upload').then(input => {
      expect(input[0].files[0].name).to.equal('sample.txt');
    });

    // Click the upload button
    cy.get('#upload-submit').click();

    // Verify the success message appears with correct text
    cy.get('#upload-success')
      .should('be.visible')
      .and('contain.text', 'File uploaded successfully!');
  });
});

The test starts by visiting the upload page before each test.

It uses cy.get('#file-upload').selectFile() to simulate selecting the file sample.txt from the fixtures folder.

Then it asserts the file input element actually contains the selected file by checking the file name.

Next, it clicks the upload button to submit the file.

Finally, it verifies the success message is visible and contains the expected text, confirming the upload succeeded.

This approach uses Cypress best practices: stable selectors, no hard waits, and clear assertions.

Common Mistakes - 3 Pitfalls
Using hardcoded waits like cy.wait(5000) after clicking upload
Using CSS selectors that are brittle like complex nth-child or class names that change
{'mistake': 'Not verifying the file input contains the selected file before submitting', 'why_bad': 'The test might pass without actually selecting the file, missing a key step.', 'correct_approach': "Assert the file input's files property to confirm the file is selected."}
Bonus Challenge

Now add data-driven testing to upload three different files: 'sample.txt', 'image.png', and 'document.pdf', verifying success for each.

Show Hint