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

如何在Jest的toHaveBeenCalledWith中验证传入的JSX内容?

验证Jest调用参数中的JSX内容

有几种实用的方法可以验证Jest调用参数里的JSX内容是否包含指定文本:

方法1:用React Testing Library渲染并查询文本

先提取出被调用时传入的JSX参数,再用测试库渲染后查询目标文本,这种方式最直观,也符合React测试的最佳实践:

// 获取setPattern方法被调用时的第一个参数
const [callParams] = store.setPattern.mock.calls[0];
const targetJSX = callParams.stepOne.res;

// 渲染目标JSX
render(targetJSX);
// 检查是否包含"red"文本(正则忽略大小写可选)
expect(screen.getByText(/red/i)).toBeInTheDocument();

方法2:直接断言JSX的结构与文本内容

如果不需要完整渲染,也可以直接通过JSX对象的属性层级断言文本,适合结构固定的场景:

expect(store.setPattern).toHaveBeenCalledWith(expect.objectContaining({
  stepOne: expect.objectContaining({
    res: expect.objectContaining({
      // 验证外层元素类型
      type: 'div',
      props: expect.objectContaining({
        children: expect.objectContaining({
          type: 'p',
          props: expect.objectContaining({
            // 验证文本包含指定内容
            children: expect.stringContaining('red')
          })
        })
      })
    })
  })
}));

注意事项

  • 如果传入的是自定义组件而非原生DOM元素,需要先传入必要props渲染组件后再做断言
  • 用正则表达式(如/red/i)可以匹配动态或大小写不固定的文本场景

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 23:31:00