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

将ReactDOM.render替换为createRoot后Jest简单测试失败如何解决?

React 18 createRoot() 测试失败解决方案

问题核心原因

React 18 中 createRoot().render() 是异步执行的,测试在调用 render 后立即执行断言时,DOM 还未完成更新,因此获取到的document.body.textContent为空,导致测试失败。而 React 17 的ReactDOM.render()是同步执行的,所以能直接通过测试。

另外还有个细节问题:你的Appointment组件目前没有接收customer props,硬编码了"Ashley",后续扩展测试会不符合TDD逻辑。

解决方法

1. 使用act()包裹渲染操作

act()会确保React的所有更新完成后再执行后续代码,是测试React组件的标准方式。需要从react-dom/test-utils导入act,将渲染逻辑包裹在act中。

修改后的test/Appointment.test.js:

import React from 'react';
import { createRoot } from 'react-dom/client';
import { act } from 'react-dom/test-utils';
import { Appointment } from '../src/Appointment';

describe('Appointment', () => {
  it("renders the customer's first name.", () => {
    const customer = { firstName: 'Ashley' };
    const component = <Appointment customer={customer} />;
    const container = document.createElement('div');
    document.body.appendChild(container);

    act(() => {
      const root = createRoot(container);
      root.render(component);
    });

    // 更精准的断言:直接检查组件容器内容,避免全局DOM污染
    expect(container.textContent).toMatch('Ashley');
  });
});

2. 修正Appointment组件(符合TDD逻辑)

当前组件未使用传入的customer props,硬编码名字不符合测试意图,建议修改组件:

import React from 'react';

export const Appointment = ({ customer }) => <div>{customer.firstName}</div>;

额外优化建议

  • 测试结束后清理DOM,避免影响其他测试用例:
afterEach(() => {
  document.body.innerHTML = '';
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 00:27:05