DEV Community

ADS-BNE
ADS-BNE

Posted on

4 handy Cypress snippets

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.

const urlInterceptResp = (link) => {
    cy.intercept('GET', '**/*').as('getRequests');
    let reportMsg = "";
    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

Top comments (0)