Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test File-Upload functionality?

I am currently in a deep dive into Cypress and writing e2e tests for an application. I seem to have hit a road block when it comes to testing file upload functionality. Due to my beginner status as a QA engineer and the lack of Internet traffic on this specific issue I have reached and impasse. I came across Cypres.Blob in the Docs. Unfortunately there is not a lot of documented and I haven't been able to apply the examples to what I need to learn.

describe ('File Upload Test', () => {
    it('should upload a file', () => {
        let testfile = cy.fixture('../fixtures/cypresstest.txt')
        cy.get('input[type=file]').then(($input) => {
        return Cypress.Blob.base64StringToBlob(testfile, 'file/txt')
            .then((blob) => {
            $input.fileupload('add', { files: blob })
            })
        })
    })
});
like image 688
Justin Oswald Avatar asked Sep 12 '25 05:09

Justin Oswald


1 Answers

I'm testing our file upload service like this:

Cypress.Commands.add('uploadFile', (fileNamePath, fileName, fileType = ' ', selector) => {
  cy.get(selector).then((subject) => {
    cy.fixture(fileNamePath, 'base64')
      .then(Cypress.Blob.base64StringToBlob)
      .then((blob) => {
        const el = subject[0]
        const testFile = new File([blob], fileName, {
          type: fileType,
        })
        const dataTransfer = new DataTransfer()
        dataTransfer.items.add(testFile)
        el.files = dataTransfer.files
      })
  })
})

Then in spec file. click upload button and wait for the file to load up:

cy.server().route('POST', api-upload-url).as('loadUp')
        cy.uploadFile('./pathToFile/' + fileName, fileName, fileType, fileInput);
        cy.get('.btn-upload.mat-raised-button.mat-primary').click()
        cy.wait('@loadUp').then((response) => {
            expect(response.method).to.eq('POST')
            expect(response.status).to.eq(200)
            expect(response.response.body.status).to.eq('OK')
        })

There's also a check for desired responses.

It's not super fancy and optimized. But it works in 3.1.5 and 3.2.0. It works using the electron 59 both headed and headless

like image 165
Radiopepper Avatar answered Sep 13 '25 19:09

Radiopepper