@mknrt/cypress-console-spy
v1.2.4
Published
Cypress plugin to monitor and handle console errors and warnings
Maintainers
Readme
@mknrt/cypress-console-spy
A Cypress plugin to monitor and handle console errors, warnings, and uncaught errors during tests. It offers configurable options, whitelisting, error statistics, and logging capabilities, with robust support for test-specific and suite-level configuration overrides.
Table of Contents
- Installation
- Setup
- Core Files
- Configuration
- Features
- Example Test
- Debug Logging
- Tasks
- Changelog
- Contributing
- Issues
- License
Installation
Install the plugin via npm:
npm install @mknrt/cypress-console-spyOlder versions (<1.1.0) are deprecated; please update to the latest version.
Setup
- Register the server part in
cypress.config.js:
const { defineConfig } = require('cypress');
const { server } = require('cypress-console-spy');
module.exports = defineConfig({
e2e: {
setupNodeEvents(on, config) {
server(on, config);
return config;
},
env: {
consoleDaemon: {
failOnSpy: true,
logToFile: true,
methodsToTrack: ['error', 'warn'],
throwOnWarning: false,
whitelist: ['socket.io', /ThirdPartyScript/, 'known warning'],
debug: false,
},
},
},
});- Register the client part in
cypress/support/e2e.js:
const { client } = require('cypress-console-spy');
client(Cypress, Cypress.env('consoleDaemon'));Core Files
The plugin consists of two main files:
- server.js: Manages server-side tasks, including logging console issues, saving them to files, sending notifications, and tracking error statistics. It defines Cypress tasks like
logConsoleError,saveConsoleErrorToFile,notifyCriticalError,getErrorStats,resetErrorStats, andsetDebugMode. It also handles events likebefore:run(to reset stats) andafter:run(to display a summary of errors and warnings). - client.js: Handles client-side functionality by overriding Cypress's
describe,it,it.only, andit.skipfunctions to wrap tests and suites. It sets up spies for specified console methods (e.g.,error,warn), captures uncaught errors via a global error handler, filters issues based on a whitelist, checks for console issues after each test, and triggers server-side tasks for logging and notifications.
Configuration
The plugin supports the following options, configurable via Cypress.env('consoleDaemon'):
failOnSpy(boolean): Fails the test if console issues are detected (default:true). Can be overridden at the suite level withdescribe('name', { consoleDaemon: { failOnSpy: false } }, () => {...})or test level withit('name', { consoleDaemon: { failOnSpy: false } }, () => {...}).logToFile(boolean): Saves console issues to[testName].login thecypress/logs/directory (default:true).methodsToTrack(array): Console methods to monitor (e.g.,['error', 'warn', 'log'], default:['error']).throwOnWarning(boolean): Treats warnings as critical, failing the test iffailOnSpyistrue(default:false).whitelist(array): Strings or RegExp patterns to ignore when checking console issues (default:[]).debug(boolean): Enables detailed debug logging in the browser console (default:false).
Suite and Test-Specific Configuration
You can override failOnSpy for entire test suites or individual tests using the consoleDaemon object:
describe('Suite with ignored console errors', { consoleDaemon: { failOnSpy: false } }, () => {
it('Test ignoring console errors', { consoleDaemon: { failOnSpy: false } }, () => {
cy.visit('https://example.com');
cy.window().then((win) => {
win.console.error('Test error'); // Won't fail the test
});
});
});Features
- Console Monitoring: Tracks specified console methods (e.g.,
error,warn) during tests. - Uncaught Error Handling: Captures uncaught errors (e.g.,
Uncaught Error: ...) and processes them with logging and notification tasks. - Whitelisting: Ignores console messages matching specified strings or patterns.
- Error Statistics: Collects and summarizes errors and warnings across test runs.
- Logging: Saves issues to files in
cypress/logs/(created automatically if the directory doesn't exist). - Suite and Test Overrides: Supports
failOnSpyoverrides at bothdescribeanditlevels for flexible configuration.
Example Test
Here’s an example demonstrating console monitoring, whitelisting, and debug mode:
describe('Test Suite with Console Spy', { consoleDaemon: { failOnSpy: false } }, () => {
it.only('Проверить чекбокс "Атрибут является хранимым"', { tags: ['@constructor', '@arm', '@arm-forms', '@regress'], consoleDaemon: { failOnSpy: false } }, () => {
// Enable debug mode for this test
cy.task('setDebugMode', true);
cy.visit('https://example.com');
cy.window().then((win) => {
win.console.error('Test error'); // Won't fail due to consoleDaemon: { failOnSpy: false }
win.console.warn('known warning'); // Ignored due to whitelist
throw new Error('Uncaught test error'); // Captured and logged
});
// Check error statistics
cy.task('getErrorStats').then((stats) => {
console.log('Error Stats:', stats);
});
});
});[Expected Behavior]:
Test erroris logged but doesn’t fail the test.known warningis ignored due to the whitelist.Uncaught test erroris captured, logged, and saved to a file (iflogToFile: true).- Debug logs appear in the browser console if
debug: true.
Debug Logging
To troubleshoot issues, set debug: true in the plugin configuration or via cy.task('setDebugMode', true). Debug logs will appear in the browser console, including:
- Configuration merging details (e.g.,
Merged config: { default, describe, test, result }). - Spy creation and collection (e.g.,
Spy created for console.error,Collected 1 calls for error). - Error checking and filtering (e.g.,
All collected issues: [...],Filtered issues: [...]). - Failure evaluation (e.g.,
Evaluating failure: filteredIssues.length=1, failOnSpy=false).
Example Debug Log:
Overriding describe with config: { consoleDaemon: { failOnSpy: false } }
Overriding it.only with config: { consoleDaemon: { failOnSpy: false } }
Merged config: { default: { failOnSpy: true, ... }, describe: { failOnSpy: false }, test: { failOnSpy: false }, result: { failOnSpy: false, ... } }
Spy created for console.error
Collected 1 calls for error
All collected issues: [{ type: "error", message: ["TEST ERROR"] }]
Filtered issues: [["TEST ERROR"]]
Evaluating failure: filteredIssues.length=1, failOnSpy=false
No failure thrown due to failOnSpy=false or no issuesLogs are saved to cypress/logs/[testName].log if logToFile: true.
Tasks
The plugin provides the following Cypress tasks:
logConsoleError: Logs console issues to the terminal.saveConsoleErrorToFile: Saves issues to[testName].logincypress/logs/.notifyCriticalError: Logs critical error notifications to the terminal.getErrorStats: Returns error and warning statistics.resetErrorStats: Resets statistics.setDebugMode: Toggles debug logging.
Changelog
[Latest Version = 1.2.3]
- Fixed Error Object Serialization: Error objects (like
AbortError) are now properly converted to readable strings instead of{}. - Fixed Whitelist Merging: Whitelists from global config, describe, and it levels are now merged together instead of overriding. This ensures global whitelist from
cypress.config.jsis always applied. - Improved Error Display: Console errors now show the actual error message (e.g., "AbortError: The user aborted a request.") instead of
{}. - Better rawMessage Extraction: Added proper extraction of error messages from Error objects and error-like objects for whitelist matching.
- Enhanced Debug Logging: Added more detailed debug logs for whitelist matching to help troubleshoot filtering issues.
[1.2.2]
- Patch version for npm publish testing.
[1.2.1]
- Simplified Config Format: Configuration now uses ONLY the
consoleDaemonkey for consistency. Use{ consoleDaemon: { failOnSpy: false } }format indescribeanditblocks.
[1.2.0]
- TypeScript Support: Added full TypeScript type definitions (
index.d.ts) for better IDE support and type safety. - Performance Optimization: Replaced multiple
cy.taskcalls with a single batch call (processConsoleBatch), significantly improving performance when multiple errors are detected. - Async File Operations: Replaced synchronous file writes with asynchronous operations in server.js to prevent blocking the Node.js event loop.
- Fixed Multiple Error Listeners: Added
WeakSettracking to prevent duplicate error event listeners on window objects during page navigation. - Improved Message Handling: Added
messageToStringutility function to safely convert any message type (arrays, objects, primitives) to strings, preventing.join()errors. - Better Type Detection: Improved
collectSpyCallsto correctly categorizeerror,warn, andinfoconsole methods instead of treating all non-errors as warnings. - Removed Hardcoded Path: Removed the hardcoded
sample.cy.jspath check fromprocessIssues. - Configurable Log Directory: Added support for custom log directory via
config.env.consoleDaemon.logDir. - Optimized Directory Creation: Log directory is now created once during
before:runinstead of checking on every file write. - Improved Debug Logging: Added consistent
[cypress-console-spy]prefix to all debug and error messages. - Backward Compatibility: Legacy task functions (
logConsoleError,saveConsoleErrorToFile,notifyCriticalError) are preserved for backward compatibility.
[1.1.4]
- CRITICAL BUG FIX: Fixed issue where tests were not failing when console errors were detected. The promise chain in
wrapTestwas incorrectly structured, causing errors thrown bycheckConsoleErrorsto not propagate properly. - Improved spy data collection: Now explicitly collects spy calls before checking errors in
wrapTest, ensuring all console errors are captured. - Fixed
setupConsoleSpyto collect data from existing spies before cleaning them up, preventing data loss during page navigation. - Added try-catch blocks around spy operations to prevent crashes when spies fail to restore or create.
- Removed redundant spy collection call from
checkConsoleErrors(now handled inwrapTest).
[1.1.3]
- Updated
setupConsoleSpyinclient.js: Removed directcy.taskcalls from thewindow.onerrorhandler. Errors are now only added to theallIssuesarray for later processing, ensuring compatibility with Cypress command chain. - Maintained error handling in
checkConsoleErrors: Ensured thatcheckConsoleErrorscorrectly processes all errors, includingResizeObservererrors, via theprocessIssuesfunction, preserving existing functionality.
[1.1.2]
- Updated readme.md
[1.1.1]
- Fixed issue with whitelist being overwritten by test or suite configurations, ensuring global whitelist from customConfig is preserved unless explicitly overridden in describe, or it blocks.
- Improved configuration merging in client.js to handle consoleDaemon properties specifically, preventing loss of whitelist and debug settings.
- Enhanced debug logging to include customConfig details for better troubleshooting.
- Updated
failOnSpyconfiguration to useconsoleDaemon: { failOnSpy: false }for test and suite overrides.
[1.1.0]
- Fixed
failOnSpy: falsenot being respected init.onlytests. - Added support for
describeblock configuration overrides. - Eliminated duplicate
checkConsoleErrorscalls for consistent behavior. - Simplified configuration merging in
client.js. - Updated
readme.mdwith new features, debug logging details, and clearer examples.
Contributing
Contributions are welcome! Please open an issue or submit a pull request on the GitHub repository.
Issues
Report problems or suggest improvements on the GitHub issues page.
License
MIT
