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

如何在Jest中避免组件重复渲染?

避免React测试中重复渲染组件的方案

你可以通过以下两种常用方法来避免重复渲染AppbarGlobal组件,同时保证测试的独立性:

方法一:使用beforeEach钩子统一渲染

在每个测试用例执行前自动渲染组件,省去每个test里重复写render的代码:

describe('AppbarGlobal [GLOBAL COMPONENT]', () => {
  // 每个测试用例执行前都会调用这个钩子,渲染新鲜的组件实例
  beforeEach(() => {
    render(<AppbarGlobal />);
  });

  test('Should be have the [TEXTS]', async () => {
    expect(screen.getByText(/dApp - Superior Electoral Court/i)).toBeInTheDocument();
  });

  test('Should be have the [COMPONENTS]', async () => {
    const logotype = screen.getByRole('img');
    const button = screen.getByText(/Connect Wallet/i);

    expect(logotype).toBeInTheDocument();
    expect(button).toBeInTheDocument();
  });

  test('Should be working the Connect Wallet [BUTTON]', async () => {
    expect(fireEvent.click(screen.getByText(/Connect Wallet/i))).toBeTruthy();
  });
});

这种方式的好处是:每个测试用例都会拿到独立的组件实例,不会出现测试之间互相干扰的情况,同时彻底消除了重复的渲染代码。

方法二:自定义复用渲染函数

如果后续需要给AppbarGlobal传递不同的props,推荐封装一个专用的渲染函数,兼顾复用性和灵活性:

describe('AppbarGlobal [GLOBAL COMPONENT]', () => {
  // 封装渲染逻辑,支持传入自定义props
  const renderAppbar = (props = {}) => {
    return render(<AppbarGlobal {...props} />);
  };

  test('Should be have the [TEXTS]', async () => {
    renderAppbar();
    expect(screen.getByText(/dApp - Superior Electoral Court/i)).toBeInTheDocument();
  });

  test('Should be have the [COMPONENTS]', async () => {
    renderAppbar();
    const logotype = screen.getByRole('img');
    const button = screen.getByText(/Connect Wallet/i);

    expect(logotype).toBeInTheDocument();
    expect(button).toBeInTheDocument();
  });

  test('Should be working the Connect Wallet [BUTTON]', async () => {
    renderAppbar();
    expect(fireEvent.click(screen.getByText(/Connect Wallet/i))).toBeTruthy();
  });

  // 示例:需要传自定义props的测试用例
  test('Should display custom title when provided', async () => {
    renderAppbar({ title: 'Custom dApp Title' });
    expect(screen.getByText('Custom dApp Title')).toBeInTheDocument();
  });
});

注意事项

不要尝试在所有测试用例之间共享同一个组件实例(比如把render放在describe外面),这会导致测试之间互相污染,一个测试的操作会影响其他测试的结果,破坏测试的独立性。

内容的提问来源于stack exchange,提问作者THIAGO DE BONIS

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 20:25:25