如何用Cypress上传txt文件进行API测试-XMLHTTPRequest



我正在尝试测试一个端点,该端点将上传一个文件并在柏树中给出200响应状态代码。根据一些研究,cy.request不能用于上传多部分/表单数据的文件,因此我们需要使用XMLHttp来上传此类文件。我创建了下面的文件来测试api,但它不起作用。有人能帮忙我的代码出了什么问题吗?非常感谢。

在support/commands.ts下添加了以下代码(我需要一个标头来从auth端点传递令牌(

// Performs an XMLHttpRequest instead of a cy.request (able to send data as FormData - multipart/form-data)
Cypress.Commands.add('multipartFormRequest', (method,URL, formData,headers, done) => {
const xhr = new XMLHttpRequest();
xhr.open(method, URL);
xhr.setRequestHeader("accept", "application/json");
xhr.setRequestHeader("Content-Type", "multipart/form-data");
if (headers) {
headers.forEach(function(header) {
xhr.setRequestHeader(header.name, header.value);
});
}
xhr.onload = function (){
done(xhr);
};
xhr.onerror = function (){
done(xhr);
};
xhr.send(formData);
})

要调用multipartFormRequest:的测试文件

const fileName = 'test_file.txt';
const method = 'POST';
const URL = "https://fakeurl.com/upload-file";
const headers = api.headersWithAuth(`${authToken}`);
const fileType = "application/text";
cy.fixture(fileName, 'binary').then((res) => {
const blob = Cypress.Blob.binaryStringToBlob(res, fileType);
const formData = new FormData();
formData.append('file', blob, fileName);
cy.multipartFormRequest(method, URL, headers, formData, function (response) {
expect(response.status).to.equal(200);
})
})

我收到以下错误消息:-现在,我的状态代码为0。

使用

const blob = Cypress.Blob.binaryStringToBlob(res, fileType); 

并移除CCD_ 1。

参见Cypress.Bob

历史

版本5.0.0
更改:
返回arrayBufferToBlob、base64StringToBlob、binaryStringToBlob和dataURLToBlob的类型方法从Promise<Blob>更改为Blob

describe("Upload image", () => {
it("upload first image", () => {
const fileName = "image.jpeg";
const method = "POST";
const url = "https://api-demo.com/1";
const fileType = "image/jpeg";
cy.fixture(fileName, "binary")
.then((txtBin) => Cypress.Blob.binaryStringToBlob(txtBin))
.then((blob) => {
const formData = new FormData();
formData.append("image_data", blob, fileName);
formData.append("image_format", "jpeg");
cy.form_request(method, url, formData, function (response) {
expect(response.status).to.eq(200)
}
);
})
});

});

Cypress.Commands.add('form_request', (method, url, formData, done) => {
const xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.setRequestHeader("device", "331231");
xhr.setRequestHeader("city", "bangalore");
xhr.onload = function () {
done(xhr);
};
xhr.onerror = function () {
done(xhr);
};
xhr.send(formData);

})

最新更新