Loop
Loop

Reputation: 237

Is there any way to read what was printed to console programatically in JS? (For testing)

I have some automated tests written in TruClient scripts and I want to verify what was printed in the application JS console.

Is there any way to access that from the javascript?

Like console.getText() type of thing?

I want to verify that some information appeared in the console.

For instance, how can I do this?

console.log("Hi");
//Now I want to check if it was printed correctly in the browser
if(console.getText() == "Hi")
{
   //then test passed
}

I am needing this because we are architecting new browsers.

Upvotes: 1

Views: 361

Answers (1)

Leftium
Leftium

Reputation: 17903

You might be able to intercept calls to console by redefining them:

// Save original console methods
var originalConsole = {
  log: console.log,
  warn: console.warn,
  error: console.error
}

var consoleHistory = [];

console.log = function() {
    // Save inputs given to console.log()
    consoleHistory.push(arguments);

    // Make call to original console
    originalConsole.log.apply(window.console, arguments);
}

// Repeat for warn and error, if needed.

Eloquent JavaScript uses this technique to display errors when evaluating JS in its code sandbox.

Upvotes: 3

Related Questions