Digging into Cypress Testing Framework

I always wanted to dig into Cypress, to see if it lives upto the hype. I suggested my employer we implement e2e testing on one of the projects and they gave me the green signal.

Awesome! Only problem, I know jack-shit about cypress.

Like the developer that I am, I headed for the docs.

Pretty straightforward installation.

npm install cypress --save-dev

On my package.json file, I added the following to the scripts section

"scripts" : {
    "cy:open": "cypress open",
    "cy:run": "cypress run"
}

The cypress open opens the tests suite on their own GUI app which can be downloaded from their site. So far, so good!

Cypress knows when if you’re a first time user, so it install a cypress directory with a number of directories within. In our case, we will be using the e2e directory to add our tests.

One awesome thing I loved about the process is that they provide a small sample todo project which contains most cypress testing utilities. You can use it to learn how to write e2e tests.

I started by testing my login page first. I wrote several test cases. I fell in love when the browser popped and ran my series of tests. On the right panel, I could see the form getting populated with the info I provided, the click events and more. Damn, it felt good.

Sure enough, with new tech comes problems.

Problem 1: I’m running the test on an app that requires authentication, and I can’t willy nilly add my credentials on the test and push it to git. I needed env variables to help. Luckily, cypress provided me with the solution. I created a cypress.env.json file in my root directory with the following

{
  "APP_URL": "http://localhost:3000",
  "TEST_USER_EMAIL": "your email address",
  "TEST_USER_PASSWORD": "your password"
}

So my initial tests becomes like this.

describe("Login", () => {
  beforeEach(() => {
    cy.visit(Cypress.env("APP_URL"));
  });

  it("form submit button enables when adding email & password", () => {
    cy.get("#email").type(Cypress.env("TEST_USER_EMAIL"));
    cy.get("#password").type(Cypress.env("TEST_USER_PASSWORD"));
    cy.get("#loginButton").should("not.be.disabled");
  });
});

I prefer Cypress’s own scoped variables rather than the OS level variables.

Problem 2: Cypress logs all the data that goes through the tests, including publicly making your email & password visible. A simple way is to turn off log for any sensitive data

it("form submit button enables when adding email & password", () => {
    cy.get("#email").type(Cypress.env("TEST_USER_EMAIL"));
    cy.get("#password").type(Cypress.env("TEST_USER_PASSWORD"), { log: false });
    cy.get("#loginButton").should("not.be.disabled");
 });

I wrote a few more tests, but I will continue to update any new stuff I learned.

Author: Soumil Roy

I'm a Frontend Engineer currently building expertise in React, TypeScript & GraphQL

Leave a Reply

Your email address will not be published.