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

Jest中test.each的字符串模板变量未被替换问题求助

解决Jest test.each标题变量不替换的问题

嗨,我来帮你搞定这个测试标题没正确渲染变量的问题~

你遇到的核心问题是:虽然Jest文档说明对象数组形式的test.each支持用$变量名替换标题内容,但单引号包裹的字符串可能因为版本兼容或解析逻辑的问题,导致变量没有被正确解析。这里有两种靠谱的解决方案:

方案一:使用标签模板写法(Jest推荐)

这种写法可读性强,Jest会自动帮你替换标题里的变量:

test.each`
  related  | value       | merging
  ${'names'} | ${'The name'} | ${true}
`('When using $related with $value then....', async ({ related, value, merging }) => {
  // Arrange
  // Act
  // Assert
  expect(...);
});

运行后测试标题就会正确输出:When using names with The name then....

方案二:用动态函数生成标题

如果更倾向于保持对象数组的传入方式,可以把标题写成一个函数,手动拼接变量内容,这种方式兼容性拉满:

test.each([{ related: 'names', value: 'The name', merging: true }])(
  ({ related, value }) => `When using ${related} with ${value} then....`,
  async ({ related, value, merging }) => {
    // Arrange
    // Act
    // Assert
    expect(...);
  },
);

函数会接收当前测试用例的对象参数,你可以完全自定义标题的生成逻辑,不用担心解析问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 15:27:43