我周末大部分时间都花在这上面,所以会发布适合我的解决方案。
我无法让 NPM 包中的示例按照cypress-upload-file-post-form
编写的方式工作。具体来说,我在Cypress.Blob.binaryStringToBlob
.
第1步
在support/commands.js
添加此功能
Cypress.Commands.add('multipartFormRequest', (method, url, formData, done) => {
const xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.onload = function () {
done(xhr);
};
xhr.onerror = function () {
done(xhr);
};
xhr.send(formData);
});
第2步
将一个名为的文件添加Base64TestCV.rtf
到该fixtures
文件夹。
我想要一个.rtf
文件,但显然你可以制作一个.txt
文件——无论你做什么,都必须使用在线转换器或base64
Linux 中的命令以 base64 编码。
出于测试目的,请确保它包含文本MyCypressTestCV
(显然以 base64 编码)。
第 3 步
创建并运行您的测试。在这个例子中,我的.rtf
文件包含MyCypressTestCV
由 httpbin.org 反射回来的文本,因此它证明它是从 base64 正确解码并上传的。
describe('Upload a file to a multipart form using cy.request', function () {
it('Performs a multipart post to httpbin.org', function () {
const baseUrl = 'http://httpbin.org';
const postUrl = `${baseUrl}/post`;
cy.visit(baseUrl); // Cypress will be very buggy if you don't do at least one cy.visit
cy.request(baseUrl).as('multipartForm'); // pretend we are doing the GET request for the multipart form
const base64FileName = 'Base64TestCV.rtf';
const postedFileName = 'TestCV.rtf';
const method = 'POST';
const mimeType = 'application/rtf';
cy.fixture(base64FileName).as('base64File'); // file content in base64
cy.get('@multipartForm').then((response) => {
const formData = new FormData();
formData.append('firstFormField', 'Hello');
formData.append('secondFormField', '25');
const blob = Cypress.Blob.base64StringToBlob(this.base64File, mimeType);
formData.append('uploadFile', blob, postedFileName);
cy.multipartFormRequest(method, postUrl, formData, function (response) {
expect(response.status).to.eq(200);
expect(response.response).to.match(/MyCypressTestCV/); // http://httpbin.org/post reflects what you post
});
});
});
});