You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vitest如何提升console.log的对象打印深度?

提升Vitest中对象日志的打印深度

有两种方案可以解决这个问题,无需依赖JSON.stringify(),就能保持默认的对象打印格式:

方案一:单个测试文件临时设置

在需要打印深层对象的测试文件开头,通过Node.js的util模块修改默认检查深度:

import { util } from 'node:util'
// 设置为null表示无限深度,也可以指定具体数值(比如10)
util.inspect.defaultOptions.depth = null

之后执行console.log({ a: { b: { c: { d: { e: 1 } } } } }),就能完整展开所有层级的对象结构。

方案二:全局配置(所有测试文件生效)

如果希望所有测试都应用该设置,可通过Vitest配置文件实现:

  1. 在项目根目录创建全局设置文件,比如setup-log-depth.js,内容如下:
import { util } from 'node:util'
util.inspect.defaultOptions.depth = null
  1. 修改vitest.config.js(或vitest.config.ts),指定该文件为全局前置脚本:
export default {
  test: {
    setupFiles: ['./setup-log-depth.js']
  }
}

保存配置后,所有测试中的console.log和console.dir都会按设置的深度展开对象。

内容的提问来源于stack exchange,提问作者Agendum

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 20:17:09