Skip to content

VirtualConsole

David Ortner edited this page Jan 21, 2025 · 6 revisions

The properties Window.console and BrowserPage.console are set to an instance of VirtualConsole by default.

VirtualConsole will not output anything to the default console for the environment. It will instead send all messages to the VirtualConsolePrinter stream.

VirtualConsolePrinter can be used to read the log messages from VirtualConsole.

Signature

class VirtualConsole extends Console

Methods

VirtualConsole has the same methods as the Node.js Console class.

Example

import { Window, VirtualConsoleLogLevelEnum } from "happy-dom";

const window = new Window();

window.console.log("Test", { test: true });

const log = window.happyDOM.virtualConsolePrinter.readAsString(
   VirtualConsoleLogLevelEnum.log
);

// Will output 'Test {"test": true}' to the NodeJS console
global.console.log(log);

Use Another Console

It is possible to replace the Virtual Console with another console (such as the Node.js console).

import { Window } from 'happy-dom';

const window = new Window({ console: global.console });

// Will output 'Test' to the Node.js console
window.console.log('Test');
Clone this wiki locally