Skip to content

nils-hoyer/cypress-fail-on-console-error

Repository files navigation

cypress-fail-on-console-error

This Plugin observes console.error() function from window object. Cypress test will fail when the error conditions are met. For observing network errors please check out cypress-fail-on-network-error.

Installation

npm install cypress-fail-on-console-error --save-dev

Usage

cypress/support/e2e.js

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

failOnConsoleError();

Config (optional)

Parameter Default
Description
consoleMessages [] Exclude console messages from throwing AssertionError. Types RegExp and string are accepted. Strings will be converted to regular expression. RegExp.test() will be used for console message matching. Make sure to escape special characters. When console message property stacktrace exists, then the whole stacktrace can be matched.
consoleTypes ['error'] Define console types for observation. error, warn, info, debug, trace , table` are accepted values.
debug false Enable debug logs for consoleMessage_configConsoleMessage_match and consoleMessage_excluded to cypress runner

import failOnConsoleError, { Config } from 'cypress-fail-on-console-error';

const config: Config = {
    consoleMessages: [
        'foo', 
        /^bar-regex.*/,
        /^((?!include-console-messages).)*$/ 
    ],
    consoleTypes: ['error', 'warn'],
};

failOnConsoleError(config);

Set config from cypress test

Use failOnConsoleError functions getConfig() and setConfig() with your own requirements. Detailed example implementation cypress comands & cypress test. Note that the config will be resetted to initial config between tests.

// Simple example implementation
const { getConfig, setConfig, ConsoleMessage } = failOnConsoleError(config);

Cypress.Commands.addAll({
    getConsoleMessages: () => cy.wrap(getConfig().consoleMessages),
    setConsoleMessages: (consoleMessages: ConsoleMessage[]) => 
        setConfig({ ...getConfig(), consoleMessages });
describe('example test', () => {
    it('should set console messages', () => {
        cy.setConsoleMessages(['foo', 'bar']);
        cy.visit('...');
    });
});

Debugging

When Cypress log is activated, debug information about the console messages / config console messages matching and excluding process are available from the cypress runner. As a plus, the generated error message string can be verified. debugTrue.png

Contributing

  1. Create an project issue with proper description and expected behaviour
  2. NPM command npm run verify have to pass locally
  3. Provide a PR with implementation and tests