简体   繁体   中英

How to test File-Upload functionality in Cypress?

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. Unfortunatly 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 })
        })
    })
})

});

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

I had this issue recently in a Laravel + React project, and I found an NPM module that's very useful for handling this called cypress-file-upload.

USAGE

  1. NPM install cypress-file-upload
  2. Import in /support/commands.js: import 'cypress-file-upload';
  3. Read cypress-file-upload Recipes for using plugin to test file uploads:

Hope this helps someone else! Many thanks to that module's author for his work.

引起我注意的是,赛普拉斯3.1.5还不支持测试文件上传功能。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM