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

使用node:test测试框架时如何获取console.log的完整输出?

问题与解决

我正在使用node:test测试运行器,测试代码中通过console.log打印内容:

console.log({ foo: JSON.stringify(choices) });

预期输出会包含JSON.stringify(choices)的执行结果,但实际运行测试命令:

node --test --test-reporter=spec src/createChat.test.ts

得到的输出却是:

ℹ {
ℹ foo:
ℹ }

原因分析

  1. 大概率是choices变量值为undefined、null,或者包含JSON无法序列化的内容(比如循环引用),导致JSON.stringify(choices)返回undefined,而node:test的spec报告器在格式化输出对象时,会省略值为undefined的属性内容。
  2. 另一种可能是spec报告器的格式化逻辑自动折叠了空值或未定义的属性显示。

解决方法

  • 排查变量有效性:单独打印choices和序列化结果,确认数据是否正常:
    console.log('原始choices:', choices);
    console.log('序列化结果:', JSON.stringify(choices));
    
  • 换打印方式绕过对象格式化:直接打印字符串而非对象,避免报告器修改输出:
    console.log(`foo: ${JSON.stringify(choices)}`);
    
  • 更换测试报告器:使用tap报告器,它会更忠实地保留原始输出内容:
    node --test --test-reporter=tap src/createChat.test.ts
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 04:27:40