2014-12-04 128 views
6

我正在JavaScript中构建一个简单的单元测试方法。输出正在控制台中打印。将样式添加到chrome中的console.table()

我希望通过测试的行是绿色的,而失败的测试是红色的(背景或文本)。

我知道我可以添加样式到console.log(),但我还没有找到添加样式到console.table()的方法。

那么,它甚至有可能吗?如果不是,将会有什么替代方案。

代码示例:

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

TNX提前!

+0

我已经更新了我的答案。让我知道它是否满足您的需求 – faby 2014-12-04 10:46:37

回答

2

即使@faby创建了一个使用console.log()的好例子,但我仍然没有发现它适用于我的问题。我也得出了将样式添加到console.table()是不可能的结论。

我想出了巢结果划分为组的解决方案,显示出在表内嵌套:

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(); 

这给出了以下的输出:

Output

5

尝试使用console.logconsole.table和使用的样式

工作和测试代码:

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

对于你的情况,你可以做到这一点

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); 

与元素取代我x您array

+0

这似乎不会影响表格,但会在样式输出中添加另一行。我喜欢这个主意,尽管 – 2014-12-04 10:23:19

+1

这个解决方案非常棒!而且它确实有效! – 2014-12-04 10:24:09

+0

@ChrisLaarman为什么不工作?我测试了我的代码。告诉我你的代码,我会尽力帮助你 – faby 2014-12-04 10:25:50