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);
}
);
});
});
});
really helpful. Thanks