Skip to content

Instantly share code, notes, and snippets.

@fityanos
Last active August 22, 2022 09:19
Show Gist options
  • Save fityanos/64a4f3fab1623877293142cba131b324 to your computer and use it in GitHub Desktop.
Save fityanos/64a4f3fab1623877293142cba131b324 to your computer and use it in GitHub Desktop.
upload images through API Cypress.io

You need to create a js file to build your helper funnction

export function XMLHttp_request(method, url, token, formData, done) {
  const xhr = new XMLHttpRequest();
  xhr.open(method, url);
  xhr.setRequestHeader("accept", "*/*");
  xhr.setRequestHeader("Authorization", `Bearer ${token}`); // only if you need token
  xhr.send(formData);
  xhr.onload = function () {
    done(xhr);
  };
  xhr.onerror = function () {
    done(xhr);
  };
}

and then, in your spec file you can test as follow

import { XMLHttp_request } from "../../../file-upload-command";
import { token } from "../../../fixtures/auth_generator";
import fixturesPath from "../../../fixtures/fixturesPath";
import httpMapper from "../../../fixtures/httpMapper";

const fileName = "selfie.png";
const method = "POST";
const url = "/content-service/content/batman";

describe(`LUMI - Content controller | POST |_.Positive`, () => {
  before(() => { // only if you require token
    /**
     * run the function before to generate and store new token
     * under -> cypress/fixtures/token.json
     */
    token();

    // load the newly generated token and store as fixture
    cy.fixture(fixturesPath.cmsTokenFixture).as("Token");
  });
  
  it("`POST |_.Upload -> Content controller :Status: 200 | Upload PNG`", function () {
    // load file from fixtures
    cy.fixture(fileName, "binary") // load the file name from fixtures in encode it as binary
      .then((txtBin) => Cypress.Blob.binaryStringToBlob(txtBin)) // conveeret the img from binray encode to Blob for JS reading
      .then((blob) => {
        const formData = new FormData(); // initiate a new request form
        formData.append("file", blob, fileName);
        XMLHttp_request(
          method,
          url,
          this.Token.token,
          formData,
          function (response) {
            let myObj = JSON.parse(response.response); // convert string to JS object
            let imgUrl = myObj.data; // get the exact image url on SDN

            console.log(imgUrl);

            expect(response.status).to.eq(httpMapper._OK_.code);
            expect(response.statusText).to.eq(httpMapper._OK_.str);
          }
        );
      });
  });
});
@afrofarmr
Copy link

really helpful. Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment