I think this is because your form is using native form submit, but Cypress' cy.route() only responds to XHR calls (at the moment).
There is a big discussion in issue #170.
Gleb Bahmutov has an interesting idea in this comment, code in this repository. Essentially he 'mocks' the native submit with an XHR submit, on the fly.
I tried out a variation which gets closer to your scenario. Follow the repository READ.ME to set up the test, but first update the Cypress version in package.json. Add the file to be uploaded into /cypress/fixtures.
Then try the following spec.
The third test is an alternative which uses cy.url() instead of cy.route().
uploadFile command (or similar variation)
Cypress.Commands.add('uploadFile', (fileName, selector) =>
cy.get(selector).then(subject => {
return cy
.fixture(fileName, 'base64')
.then(Cypress.Blob.base64StringToBlob)
.then(blob => {
const el = subject[0];
const testFile = new File([blob], fileName, {
type: 'application/vnd.openxmlformatsofficedocument.spreadsheetml.sheet',
});
const dataTransfer = new DataTransfer();
dataTransfer.items.add(testFile);
el.files = dataTransfer.files;
return subject;
});
})
);
Function to 'mock' the native submit with XHR (place at top of Spec)
const mockNativeSubmitWithXhr = (form$) => {
let win
cy.window().then(w => {
win = w
})
form$.on('submit', e => {
e.preventDefault()
const form = new FormData(e.target)
const XHR = new win.XMLHttpRequest()
XHR.onload = response => {
win.document.write(XHR.responseText)
win.history.pushState({}, '', XHR.url)
}
XHR.open(e.target.method, e.target.action)
XHR.send(form)
return true
})
}
Spec
describe('waiting for form-data post', () => {
beforeEach(() => {
cy.task('deleteFile', '../../uploads/Sample_data.xlsx')
cy.visit('localhost:3000')
cy.get('input[name="userid"]').type('foo@bar.com')
})
it('upload with native form submit (fails because of native event)', () => {
cy.server()
cy.route('POST', '/upload').as('upload');
cy.uploadFile('Sample_data.xlsx', '[id=fileToUpload]')
cy.get('input[type="submit"]').click()
cy.wait('@upload');
cy.readFile('uploads/Sample_data.xlsx') // check saved file
})
it('upload with form submit mocked to XHR send (succeeds)', () => {
cy.server()
cy.route('POST', '/upload').as('upload');
cy.uploadFile('Sample_data.xlsx', '[id=fileToUpload]')
cy.get('form').then(form => mockNativeSubmitWithXhr(form))
cy.get('input[type="submit"]').click()
cy.wait('@upload');
cy.readFile('uploads/Sample_data.xlsx')
})
it('upload with native form submit (testing url has changed)', () => {
cy.uploadFile('Sample_data.xlsx', '[id=fileToUpload]')
cy.get('input[type="submit"]').click()
cy.url().should('eq', 'http://localhost:3000/upload')
cy.readFile('uploads/Sample_data.xlsx')
})
})
Task to remove uploaded file between tests (modify '/cypress/plugins/index.js')
const fs = require('fs')
module.exports = (on, config) => {
on('task', {
deleteFile: (path) => {
if (fs.existsSync(path)) {
fs.unlinkSync(path)
}
return null
}
})
}