How to Upload txt file with Cypress for API Testing - XMLHTTPRequest?(如何用Cypress上传txt文件进行API测试-XMLHttpRequest?)
问题描述
我正在尝试测试一个端点,它将上传一个文件,并在Cypress中给出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);
并删除.then()。
参见Cypress.Blob
历史记录
版本5.0.0
更改:
arrayBufferToBlob、base64StringToBlob、binaryStringToBlob和dataURLToBlob方法的返回类型从Promise<Blob>更改为Blob
这篇关于如何用Cypress上传txt文件进行API测试-XMLHttpRequest?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何用Cypress上传txt文件进行API测试-XMLHttpRequest?
基础教程推荐
- npm start 错误与 create-react-app 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- Bokeh Div文本对齐 2022-01-01
