【问题标题】:Cypress Error making HTTP POST with File in request bodyCypress 使用请求正文中的文件进行 HTTP POST 时出错
【发布时间】:2021-04-09 14:49:35
【问题描述】:

我从 Cypress 6.8.0 升级到 7.0.1。升级后,当 Cypress 测试之一调用此函数时

async saveTask (task, file) {
  const requestBody = new FormData()
  requestBody.append('file', file)

  return await http.post('/api/endpoint', requestBody, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
},

我收到以下错误

TypeError [ERR_INVALID_ARG_TYPE] [ERR_INVALID_ARG_TYPE]: 
The first argument must be of type string or an instance of Buffer or Uint8Array. Received type number (45)
    at write_ (_http_outgoing.js:696:11)
    at ClientRequest.write (_http_outgoing.js:661:15)
    at Request.write (/Users/donal/Library/Caches/Cypress/7.0.1/Cypress.app/Contents/Resources/app/packages/server/node_modules/@cypress/request/request.js:1496:27)
    at /Users/donal/Library/Caches/Cypress/7.0.1/Cypress.app/Contents/Resources/app/packages/server/node_modules/@cypress/request/request.js:546:20
    at Array.forEach (<anonymous>:null:null)
    at end (/Users/donal/Library/Caches/Cypress/7.0.1/Cypress.app/Contents/Resources/app/packages/server/node_modules/@cypress/request/request.js:545:23)
    at Immediate._onImmediate (/Users/donal/Library/Caches/Cypress/7.0.1/Cypress.app/Contents/Resources/app/packages/server/node_modules/@cypress/request/request.js:578:7)
    at processImmediate (internal/timers.js:461:21)
 {
  code: 'ERR_INVALID_ARG_TYPE'
}

我用来发出 POST 请求的 http 对象是一个 Axios 实例,而我附加到请求正文的 file 对象是一个 File。文件对象是问题的原因,因为如果我不将其附加到请求正文中,则不会发生错误。

该错误仅在 Cypress 测试运行该函数时发生。 Cypress 使用 Node.js,从上面的错误消息来看,似乎不允许使用 File 类型。另外Axios request config docs表示Axios在Node下运行时,File是不允许的。

  // `data` is the data to be sent as the request body
  // Only applicable for request methods 'PUT', 'POST', 'DELETE , and 'PATCH'
  // When no `transformRequest` is set, must be of one of the following types:
  // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
  // - Browser only: FormData, File, Blob
  // - Node only: Stream, Buffer
  data: {
    firstName: 'Fred'
  },

所以我想我需要将File 对象转换为其他东西,这样这个函数就可以在应用程序本身以及由赛普拉斯运行时工作。

在服务器端(Spring Boot 应用程序),此文件绑定到 MultipartFile

public void handlePost(
    RequestPart(value = "file") MultipartFile file) {

    // controller action body       
}

如果我认为File 类型是问题所在,我应该改用什么以及如何进行转换?

【问题讨论】:

标签: javascript node.js axios cypress


【解决方案1】:

该错误仅在 Cypress 测试运行该函数时发生。 Cypress 使用 Node.js,从上面的错误消息来看,它似乎 文件类型不允许。此外,Axios 请求配置 文档指出,当 Axios 在 Node 下运行时,不允许使用 File。

默认情况下,Cypress 以无头模式启动 Electron,即测试始终可以访问浏览器 API。您可以控制要在哪个浏览器上运行测试。更多详情here.

现在我们来看看文件上传的解决方案

假设您在函数saveTask 中引用的filetype=filename=fileinput 字段。

假设您需要上传一个名为email.png 的png 图像,该图像位于cypress/fixtures/images/email.png

使用以下代码块上传文件。

 cy.fixture('images/email.png').as('emailImage')
   cy.get('input[name=file]').then(function (el) {
     const blob = Cypress.Blob.base64StringToBlob(this.emailImage, 'image/png')
     const file = new File([blob], 'email.png', { type: 'image/png' })
     const list = new DataTransfer()
     list.items.add(file)
     el[0].files = list.files
     el[0].dispatchEvent(new Event('change', { bubbles: true }))
 })
 

现在您可以触发调用您的上传api(/api/endpoint)的操作,并最终验证上传是否成功。

 // Trigger the action which causes the upload api to be invoked e.g. clicking on a button
 cy.get('input[type=button]').click();
 
 // Verify the api invocation is successful (The below code checks a div with id result to have the String 'Success')
 cy.get('#result').should('contain', 'Success');

您可以上传任何类型的文件,而不必是图片。有关更多信息,请查看 fixtureBlob。此答案基于 Blob 文档上的 example

此 repo 使用 GitHub Actions https://github.com/GSSwain/file-upload-cypress-test 在 CI 上运行测试,服务器是 Spring Boot 应用程序(在 CI 服务器上作为 Docker 容器运行)代码位于 https://github.com/GSSwain/file-upload-ajax-sample

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-05
  • 2020-09-10
  • 1970-01-01
  • 1970-01-01
  • 2019-11-16
  • 2015-11-03
  • 2015-06-26
相关资源
最近更新 更多