DEV Community

Cover image for 4 handy snippets for your Cypress tests
ADS-BNE
ADS-BNE

Posted on • Edited on

4 handy snippets for your Cypress tests

This is the start of my growing list of handy JavaScript code snippets for the Cypress Testing Framework. I will update as I go.

Checking something includes “either/or” with “satisfy”

In this example we're checking if the page's URL includes one of 2 strings.

cy.url().should('satisfy', (url) => {
    return url.includes(pathStringA) || url.includes(pathStringB);
})
Enter fullscreen mode Exit fullscreen mode

Get an element’s tag type

Check what tag and element has eg <a>, <div>, <h1> etc

cy.get('.heading').then(($element) => {
    const tagName = $element[0].tagName;
    cy.task('log', tagName); // returns 'H1'
});
Enter fullscreen mode Exit fullscreen mode

Check if an element exists (or doesn’t exist)

Simply check if an element with a given class or ID exists on the page or not.

cy.get('body').then(($body) => {
  if ($body.find('.some-element').length == 0) {
    //do something if element doesn't exist
  }
  else {
    //do something if element does exist
  }
});

Enter fullscreen mode Exit fullscreen mode

Checking URL statuses and redirects

Check if a given URL is working and if it is or isnt' a redirect. This can be handy for reporting which links are redirects.

const urlInterceptResp = (link) => {
    cy.intercept('GET', '**/*').as('getRequests');
    let reportMsg = ""; // reportMsg = the output
    cy.visit(link).then(() => {
        cy.wait('@getRequests').then((interception) => {
            if (interception.response.statusCode >= 300 && interception.response.statusCode < 400) {
                reportMsg = `is working, and redirecting to ${interception.response.headers.location}`;
            }
            else {
                reportMsg = `is working normally`;
            }
            cy.task('log', `${link}: ${reportMsg}`);
        });
    });
    // If visit() fails then intercept() won't run so we log errors this way.
    cy.on('fail', (err, runnable) => {
        cy.task('log', `${link}: ${err}`);
        throw new Error(`${testName + ' ' + link}: fail. ${err}`);
    });
}

Enter fullscreen mode Exit fullscreen mode

Cover photo by Madzery Ma

Top comments (0)