如何使用请求通过Cypress向服务器发送二进制文件
在测试之前,我需要直接从Cypress API向服务器上传一个excel表(无需任何输入[type=“file”],只需提交普通文件),然后它将与一些其他数据一起请求返回,并由测试使用 所以我尝试了不同的方法让Cypress通过fixture使用文件,用不同的数据编码读取文件,但是neigther不起作用 一旦成功接收到文件,就必须运行一些剩余的代码如何使用请求通过Cypress向服务器发送二进制文件,cypress,Cypress,在测试之前,我需要直接从Cypress API向服务器上传一个excel表(无需任何输入[type=“file”],只需提交普通文件),然后它将与一些其他数据一起请求返回,并由测试使用 所以我尝试了不同的方法让Cypress通过fixture使用文件,用不同的数据编码读取文件,但是neigther不起作用 一旦成功接收到文件,就必须运行一些剩余的代码 before(() => { cy.fixture("data/catalog.xlsx", "binary") .the
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
})
我发现无论是cy.request还是Cypress.$.ajax都不能处理文件 我的问题隐藏在两个问题中:
- 获取一个文件以从本地发送:
- 将其准备为二进制文件:
- 将其作为数据提交的一部分:
- 尽管cy.Request或Cypress$.ajax,请求解决方案:
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");
});
你能展示一下你想要点击的API控制器的模型吗。顺便说一下,这是什么错误?@ Prany,谢谢你的帮助,但是API确实是正确的,但是CyPress根本不使用新的FrasDATA,我发现了一些关于它的bug,但是如果你添加<代码>表单:Trase< /Cord>它会考虑输入为表单数据吗?@ Prany,你的意思是放置表单:Trand,它是什么?因为在我的例子中,没有任何输入字段来获取测试前放置的文件,所以它存储在localy中,并直接将文件发送到服务器apione。但是这里有一个问题。等待(“@formRequest”)继续等待,没有响应。我试图将超时时间增加到60秒。但它仍在等待。我只是删除了断言,直到找到一个解决方案:我删除了.wait(@formRequest),并在xhr.send(formData)之后添加了这个断言;xhr.onreadystatechange=function(){//在状态更改时调用函数。if(this.readyState==XMLHttpRequest.DONE&&this.status==200){//请求已完成。在此处执行处理。}
.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.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");
});