Write and Read data in CypressIO

Writing the data into JSON and txt file

In cypress, we can write data in a JSON file, txt file using the command cy.writeFile()and we can also retrieve the data from the files.

Syntax

//To write in JSON file
 cy.writeFile("Filename.json", { "Data" });
//To write in txt file
cy.writeFile("Filename.txt", "Data");

Example program :

describe("write and read data into JSON", () => {
  it("should write data into JSON", () => {
    cy.writeFile("log.json", { name: "John", age: 25 });
  });
  it("should write data to the text file", () => {
    cy.writeFile("log.txt", "Cherchertech");
  });
});

Output :

output-json-txt

In the explorer, two different files with the given values are created in the .json and .txt format like the below image,

json-txt-file-creation

Read and verify data in JSON and txt file

To read or verify data, the file must exist in cypress. To read the data from the JSON or txt file, The below syntax is used.

Syntax

//To read data from JSON file
cy.readFile("filename.json")
//To read data from txt file
cy.readFile("filename.txt")

Example program :

describe("write and read data into JSON", () => {
  it("should write data into JSON", () => {
    cy.writeFile("log.json", { name: "John", age: 25 });
  });
  it("should write data to the text file", () => {
    cy.writeFile("log.txt", "Cherchertech");
  });
  it("should read and verify data from JSON file", () => {
    cy.readFile("log.json").its("age").should("eq", 25);
  });
  it("should read and verify data from text file", () => {
    cy.readFile("log.txt").should("eq", "Cherchertech");
  });
});

Output :

read-verify-output-cypress

Verifying the data from the browser document

In cypress, we can even verify the loaded webpage document contents with the help of the command cy.document(). Let us understand it with the help of an example,

Example program :

describe("Verifing the document in the browser", () => {
  it("should read and verify browser content", () => {
    cy.visit("https://chercher.tech/");
    cy.wait(2000);
    cy.document().its("contentType").should("eq", "text/html");
    //checking whether the document is in text/html format
    cy.document().should("have.property", "charset").and("eq", "UTF-8");
    //checking whether the document has a charset propery and whether it is equal to UTF-8
  });
});

Output :

verifying-document-in-browser

Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions