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!
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:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With