In this tutorial. I will share some code-snippets I have found useful when writing tests using Cypress.  For those of you new to Cypress I suggest you start here.

Skeleton Class

First, let's start with a skeleton class to get us going:

describe(", ()=>{
    before(()=>{
      cy.clearCookies()
    });

    it('', ()=> {
    });
});

Basics

Next, let's go over some of the go-to snippets you will be using time and time again:

Go To A Page
cy.visit(/myUrl');
Clicking A Button
cy.get('#buttonId').click();
Creating A Pause
cy.wait(50);
Setting And Clearing Cookies
cy.setCookie('cookiName', 'someValue');
cy.clearCookies();
Make An Element Visible On The Page
cy.get('.myClass').scrollIntoView();
Stubbing A Response
  • Use cy.server() to start a Cypress instance to store your stubbed requests
  • Define your stubbed requests using, cy.route()
Creating An Alias
cy.route('GET', userSummary, 'fx:responses/user/userSummary_NonEIP').as('myAlias');
cy.wait(['@myAlias']);

Configuring Cypress

To get certain tests to work, you may need to change Cypress default behaviour. In this section, I'll cover my most used snippets.

Disabling Uncaught Exceptions

On your page, you may have any scripts/async requests that fail with an uncaught exception error, by default this will fail your test. This can be annoying if the thing that fails - like an analytics request failing - is stopping you testing something meaningful. In these situations, in your test class you can tell Cypress to ignore these errors, like so:

export function toogleUncaughtException(enabled){
    Cypress.on('uncaught:exception', (err, runnable) => {
        return enabled;
      });
}