Useful Code Snippets To Help You Write Cypress Tests

In this tutorial. I will share some code-snippets I have found useful when writing test 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(", ()=>{

    it('', ()=> {


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

Go To A Page
Clicking A Button
Creating A Pause
Setting And Clearing Cookies
cy.setCookie('cookiName', 'someValue');
Make An Element Visible On The Page
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');

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;

submit to reddit

Jon D Jones

Software Architect, Programmer and Technologist Jon Jones is founder and CEO of London-based tech firm Digital Prompt. He has been working in the field for nearly a decade, specializing in new technologies and technical solution research in the web business. A passionate blogger by heart , speaker & consultant from England.. always on the hunt for the next challenge

Back to top