Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add styles to console.table() in chrome

I am building a simple Unit-test method in JavaScript. The output is being printed in the console.

I want the rows of the passed tests to be green, and the failed tests to be red (background or text).

I know I can add styles to the console.log(), but I have not found a way to add styles to the console.table().

So, is it even possible? If not, what would be an alternative.

Code example:

console.table([
    {
        status:   'failed',
        function: 'Validate.int',
        asserted: true,
        result:   false
    },{
        status:   'passed',
        function: 'Validate.float',
        asserted: true,
        result:   true
    }
]);

Tnx in advance!

like image 647
Chris Laarman Avatar asked Dec 04 '14 09:12

Chris Laarman


2 Answers

Even though @faby created a nice example to use the console.log(), I still didn't found it applicable for my problem. I did also come to the conclusion that adding styles to the console.table() is not possible.

I came up with a solution that nests the results into groups, showing the table nested inside:

console.groupCollapsed('Testing unit: %s', unit);
for (var r in results) {
    var res = results[r];
    console.groupCollapsed('%c  %c' + res.status, 'background-color: ' + (res.status === 'failed' ? 'red' : 'green') + '; margin-right: 10px', 'background-color: transparent');
    console.table({
        Result:   {value: res.status},
        Function: {value: res.function},
        Asserted: {value: res.asserted},
        Returned: {value: res.returned}
    });
    console.groupEnd();
}
console.groupEnd();

This gives the following output:

Output

like image 132
Chris Laarman Avatar answered Oct 09 '22 14:10

Chris Laarman


Try using console.log inside console.table and use the styles

working and tested code:

console.table(console.log('%c test1 ', 'background: #cdcdcd; color: #000000'),console.log('%c test2 ', 'background: #ff0000; color: #ffffff'));

for your case you can do this

var x = {
            status: 'failed',
            function: 'Validate.int',
            asserted: true,
            result: false
        };

console.table(
        console.log('%c '+ x.status + x.function  + ' ', 'background: #cdcdcd; color: #000000'), add other elements of the array);

replace my x with elements of your array

like image 33
faby Avatar answered Oct 09 '22 14:10

faby