我想将JSON.stringify()'d对象打印到控制台,作为Mocha测试套件输出的一部分。
当测试缩进时,我希望对象日志行向右缩进足够远(例如,3-4个制表符空格),以便它们在正确的describe()组中可识别。
我如何使用像console.log或process.stdout.write这样的东西来实现这一点?
发布于 2015-09-13 01:05:29
如果仅用于console.log,您可能想要查找组,请在控制台上检查以下内容:
var obj = {
a : 1,
b : 2,
c: 3
}
console.log('Non-tabbed');
console.group();
console.log(JSON.stringify(obj, null, 2));
console.groupEnd();
console.log('Back to non-tabbed');
在当前浏览器和最新节点上运行良好。如果您使用的是较旧的节点版本,npm上也有一个包可以解决这个问题。
这会将整个JSON字符串移动3个空格。它用新的行断开JSON字符串,然后在每行上添加3个空格到一个新的字符串中,该字符串将保留每一行的移位。
var results = document.getElementById('results');
var obj = {
a: 5,
b: 3,
c: 4
};
var string = JSON.stringify(obj, null, 2);
var stringShifted = '';
string.split('\n').forEach(function(line){
stringShifted += ' ' + line + '\n';
});
console.log(string);
console.log(stringShifted);
results.innerHTML = 'Before : \n' + string;
results.innerHTML += '\n\nAfter : \n' + stringShifted;<pre id="results"></pre>
发布于 2016-01-30 03:12:40
您可以在JSON.stringify输出中添加一个简短的reg-ex替换,以获得您想要的效果。
var myObject = _buildAnObject();
it("Should log my entire JSON.stringify indented", function(){
console.log("My log message: \n\t"
+ JSON.stringify(myObject, null, 2).replace(/\n\r?/g, '\n\t'));
assert(true);
});我已经在codepen.io上放了一个可以工作的摩卡示例。
发布于 2022-02-13 11:49:01
在nodejs下,你可以尝试util.inspect(obj, {depth:10, colors:true ...}),我在mocha tested下使用它来缩进日志
const log = (...args:unknown[])=>{
setTimeout(()=>{
let indent = "\t";
args = args.map(a=>util.inspect(a, {colors:true, depth:10}).replace(/^\x1B\[32m['"`]/ig, '\x1B[32m').replace(/['"`]\x1B\[39m$/ig, '\x1B[39m').replace(/\n/g, `\n${indent} `))
console.log.call(console, indent, ...args);
})
}
let user = {
name:"surinder singh",
age:38,
hobbies:[{
name:"Something interesting",
from:"birth"
},{
name:"Electronic DIY",
from:"from ~primary"
},{
name:"Coding",
from:"after school"
}]
}
let args = ["a string 1234", 123 , {xyz:"xyz", num:123, arr:["xxx", 123, {345:"xxx"}, user], bool:true}];
console.log( ...args );
log( ...args )

https://stackoverflow.com/questions/32540948
复制相似问题