Reputation: 179
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 })
})
})
})
});
Upvotes: 4
Views: 14055
Reputation: 101
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
Upvotes: 7
Reputation: 5764
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
Hope this helps someone else! Many thanks to that module's author for his work.
Upvotes: 3