本文介绍了如何用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测试
发布评论