'How to have Cypress go through every page on site to see if there are any console errors and if so, make it known to the user running the test

I want Cypress to go through every page to see on a website to see if there are any console errors and if so, make it known to the user running the test. (I'm thinking it would be useful for CSP checking to see if the site is throwing a console error because of a domain not being whitelisted.)



Solution 1:[1]

This package cypress-fail-on-console-error may make it easier

test

import failOnConsoleError from 'cypress-fail-on-console-error';

failOnConsoleError();

const pages = [ "/page1", "/page2" ]

pages.forEach(page => {
  it(`verifies the page ${page}`, () => {
    cy.visit(page)                       
  })
})

There's some interesting stuff on Cypress and CSP here

Testing Content-Security-Policy using Cypress ... Almost

Solution 2:[2]

You can use a combination of Cypress functionality to achieve this. You could store the list of links in an array of strings, use Cypress Lodash to iterate through each string as a separate test, and use the onBeforeLoad callback within cy.visit() to spy on console.error.

describe('Tests', () => {
  // Define links
  const links = ['/1', '/2', '/3'...]

  // Iterate through the links array using Cypress Lodash
  Cypress._.times(links.length, (index) => {
    it('validates site loads with no errors', () => {
      cy.visit(links[index], {
        // set the `onBeforeLoad` callback to save errors as 'error'
        onBeforeLoad(win) {
          cy.stub(win.console, 'error').as('error');
        }
      });
      // Validate error was not called
      cy.get('@error').should('not.have.been.called');
    });
  });
});

A good deal of this answer was taken from this answer.

Solution 3:[3]

If you'd like to be specific about the errors that fail, try catching uncaught:exception

Cypress.on('uncaught:exception', (err) => {
  if (err.message.includes('Content Security Policy')) {
    return true
  } else {
    return false  // only fail on the above message
  }
})

describe('Testing Content Security Policy', () => {
  const pages = [ "/page1", "/page2" ]
  pages.forEach(page => {
    it(`visiting page ${page}`, () => {
      cy.visit(page)
    })
  })
})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 agoff
Solution 3 Fody