在测试之前,我需要直接从赛普拉斯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
})
答案 0 :(得分:0)
我发现 cy.request 和 Cypress。$。ajax 都根本无法处理文件。
我的问题隐藏在两个问题中:
以下是一些需要考虑的细节:
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.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");
});