如何通过Cypress使用请求将二进制文件发送到服务器

时间:2020-02-19 16:42:52

标签: cypress

在测试之前,我需要直接从赛普拉斯API上传到服务器的excel表(无需任何 input [type =“ file”] ,只需提交纯文件),然后将其请求返回一些其他数据,供测试使用。

因此,我尝试以各种方式使赛普拉斯通过 fixture readfile 使用具有不同数据编码的文件,但neigther仍在工作。

成功接收文件后,必须运行其余部分代码。

  before(() => {

  cy.fixture("data/catalog.xlsx", "binary")
    .then(content => {

      cy.wrap(Cypress.Blob.binaryStringToBlob(content, "utf8"))
        .then(blob => {

          const file = new File([blob], "catalog-table", {type: "utf8"});

          cy.request("POST", "http://localhost:28080/app/admin/api/catalog/import/xlsx", file)
            .then(res => {debugger; expect(res.ok).to.be.true})
            .as("fileSend");

          cy.wait("@fileSend")
            .then(() => {some other code to be executed});
        })
    })
})

还尝试添加更多的标题行

          cy.request({
            method: "POST",
            url: "http://localhost:28080/app/admin/api/catalog/import/xlsx",
            headers: {
              contentType: false,
              processData: false,
            },
            cache: 'no-cache',
            body: file
          })

1 个答案:

答案 0 :(得分:0)

我发现 cy.request Cypress。$。ajax 都根本无法处理文件。

我的问题隐藏在两个问题中:

  1. 提交前处理文件的方式;
  2. 错误的本地柏树请求方法

以下是一些需要考虑的细节:

  • 获取文件以从本地分发它:
before(() => { //run before the tests
  cy.fixture(filePath, "binary")
  • 将其准备为二进制文件:
    .then(Cypress.Blob.binaryStringToBlob)
    .then(blob => {
      const file = new File([blob], fileName);
  • 将其作为数据提交的一部分:
      let data = new FormData();

      //settings for host server
      data.append("catalogName", fileName);
      data.append("xlsxFile", file);
    尽管使用 cy.request Cypress。$。ajax
      cy.form_request(url, data)
        .then(response => { some other code})
    })
})

因为 Cypress。$。ajax 被非法调用,但是在网络上很难找到问题的根源。 柏树 formData 准备中崩溃; 我发现在Devtool的 Network 部分中,没有任何XHR请求,因为它从一开始就失败了。

我通过native XHR workaround找到了第三条路 并且在commands.js中放置了自定义请求 cy.form_reques


Cypress.Commands.add("form_request", (url, formData) => {
  return cy
    .server()
    .route("POST", url)
    .as("formRequest")
    .window()
    .then(win => {
      var xhr = new win.XMLHttpRequest();
      xhr.open("POST", url);
      xhr.send(formData);
    })
    .wait("@formRequest");
});

相关问题