当没有输入类型=“文件”时在Cypress中上传文件

问题描述 投票:0回答:2

我需要上传一个文件,但问题是该按钮没有标签输入和 attr type="file"。我该如何解决这个问题? DOM:

我尝试过:

cy.contains('div#dropdown-grouped', "Bon d'intervention").siblings('div.d-none').find('input[type="file"]') 
    .selectFile('cypress/fixtures/bon.pdf', {force: true})

但这会返回 statusCode 422

还尝试过:

const filePath = 'My reportis.jpg'
    cy.contains('#dropdown-group-1', "Bon d'intervention").attachFile(filepath)

但这显然没有任何作用。

如果我将按钮的标签从按钮更改为输入,并添加 attr type="file",会怎么样?如果是,我如何用 cypress 更改标签?

非常感谢!

解决方案:

cy.contains('#dropdown-group-1', "Bon d'intervention").click()
cy.get('input[type="file"]').selectFile('cypress/fixtures/bon.pdf', {force: true})
file-upload upload cypress cypress-file-upload
2个回答
0
投票

您的第一个代码是正确的,

cy.contains('div#dropdown-grouped', "Bon d'intervention")
  .siblings('div.d-none')
  .find('input[type="file"]')
  .selectFile('cypress/fixtures/Call order.pdf', {force: true})

状态代码 422 是来自服务器的响应,因此

selectFile()
有效并且应用程序触发了 POST,但服务器不喜欢它所给出的内容。

422 无法处理的实体

超文本传输协议 (HTTP) 422 Unprocessable Entity 响应状态代码表示服务器理解请求实体的内容类型,并且请求实体的语法正确,但无法处理所包含的指令。


从进一步的讨论来看,遵循用户采取的步骤似乎可以进行工作测试,这意味着在 selectFile() 之前添加一个按钮 click()。

这是最终的工作测试:

cy.contains('#dropdown-group-1', "Bon d'intervention").click() 

cy.get('input[type="file"]')
  .selectFile('cypress/fixtures/bon.pdf', {force: true})

0
投票

发布此内容以防它可以帮助某人。我遇到了类似的问题,在我的 Angular 应用程序中隐藏了输入。我的测试失败了,所以我的解决方案是删除隐藏我的输入的类,之后我就可以选择并上传我的文件。见下图:

  <button mat-raised-button type="submit" (click)="fileUploadInput.click()" data-cy="upload-button">
    Upload file
      <input type="file" (change)="uploadFile($event)" accept=".csv, text/csv" #fileUploadInput class="fakeInput" data-cy="upload-input">
  </button>

样式表.css

.fakeInput {
  visibility: hidden;
}

测试.规格.ts

  it('Uploads CSV file', () => {
    cy.get('[data-cy="upload-button"]').click()
    cy.get('[data-cy="upload-input"]').invoke('removeAttr', 'class') // <= removes class and makes element visible
.click().selectFile('cypress/fixtures/items.csv', )
    cy.contains('items.csv').should('exist')
  })
© www.soinside.com 2019 - 2024. All rights reserved.