我认为这是因为您的表单使用本机表单提交,但赛普拉斯的 cy.route() 仅响应 XHR 调用(目前)。
issue #170有大讨论。
Gleb Bahmutov 在 comment 中有一个有趣的想法,在 repository 中编写代码。本质上,他使用 XHR 提交“模拟”本地提交,即时。
我尝试了一种更接近您的场景的变体。按照存储库 READ.ME 设置测试,但首先在 package.json 中更新 Cypress 版本。将要上传的文件添加到/cypress/fixtures。
然后尝试以下规范。
第三个测试是使用cy.url() 而不是cy.route() 的替代方法。
uploadFile 命令(或类似变体)
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;
});
})
);
使用 XHR“模拟”本机提交的功能(位于规范顶部)
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
})
}
规格
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')
})
})
在测试之间删除上传文件的任务(修改“/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
}
})
}