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

编程入门 行业动态 更新时间:2024-10-12 03:26:33
本文介绍了如何用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 = "fakeurl/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测试

本文发布于:2023-11-24 19:46:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1626573.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何用   上传   文件   测试   txt

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!