如何测试文件上传功能?

How to test File-Upload functionality?

我目前正在深入研究 Cypress 并为应用程序编写 e2e 测试。在测试文件上传功能时,我似乎遇到了障碍。由于我作为 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')
        })

还会检查所需的响应。

它不是超级花哨和优化的。但它适用于 3.1.5 和 3.2.0。它使用电子 59 有头和无头

我最近在一个 Laravel + React 项目中遇到了这个问题,我发现了一个 NPM 模块,它对处理这个问题非常有用,叫做 cypress-file-upload。

用法

  1. NPM 安装 cypress-file-upload
  2. 在 /support/commands.js 中导入:导入 'cypress-file-upload';
  3. 阅读 cypress-file-upload Recipes 使用插件测试文件上传:

希望这对其他人有帮助! 非常感谢该模块的作者所做的工作。