我目前正在深入研究 Cypress 并为应用程序编写端到端测试。在测试文件上传功能时,我似乎遇到了障碍。由于我作为 QA 工程师的初学者身份以及在这个特定问题上缺乏 Internet 流量,我已经陷入僵局。我遇到了Cypres.Blob在文档中。不幸的是,没有很多文档,我无法将这些示例应用到我需要学习的内容中。
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 })
})
})
})
});
最佳答案
我正在像这样测试我们的文件上传服务:
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
})
})
})
然后在规范文件中。单击上传按钮并等待文件加载:
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')
})
还会检查所需的响应。
它不是 super 花哨和优化的。但它适用于 3.1.5 和 3.2.0。它使用有头和 headless 电子 59 工作
关于javascript - 如何测试文件上传功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54889492/