lundi 19 avril 2021

How to Upload txt file with Cypress for API Testing - XMLHTTPRequest?

I'm trying to test an endpoint which will upload a file and give 200 response status code in cypress. As per some research cy.request cannot be used to upload a file for multipart/form-data so we need to use XMLHttp to upload such files. I have created below file to test the api but it doesn't work. Can someone please help what's wrong with my code ? Thank you.

Added below code under support/commands.ts(I will require a header to pass token from auth endpoint)

// Performs an XMLHttpRequest instead of a cy.request (able to send data as FormData - multipart/form-data)
Cypress.Commands.add('form_request', (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);
})

Test file to call 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) => {
                        Cypress.Blob.binaryStringToBlob(res, fileType).then((blob) => {
                            const formData = new FormData();
                            formData.append('file', blob, fileName);

                            cy.multipartFormRequest(method, URL, headers, formData, function (response) {
                                expect(response.status).to.equal(200);
                            })
                        })

I'm getting this error message:- Cypress.Blob.binaryStringToBlob(...).then is not a function.

Aucun commentaire:

Enregistrer un commentaire