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

React Native单元测试报错:无法访问已卸载测试渲染器的.root

解决React Native Testing Library测试报错:Can't access .root on unmounted test renderer

问题场景

使用react-native-testing-library测试应用时,运行LoginScreen组件的渲染测试失败,触发如下报错:

Can't access .root on unmounted test renderer

There seems to be an issue with your configuration that prevents React Native Testing Library from working correctly.
Please check if you are using compatible versions of React Native and React Native Testing Library.

Can't access .root on unmounted test renderer

依赖版本

  • React版本:"react": "18.2.0"
  • React Native版本:"react-native": "0.72.3"
  • React Native Testing Library版本:"@testing-library/react-native": "^12.2.2"
  • Testing Library Jest Native版本:"@testing-library/jest-native": "^5.4.3"

原测试代码

describe('LoginScreen', () => {
  it('should render the LoginScreen component', async () => {
    await act(async () => {
      render(
        <Provider store={store}>
          <LoginScreen />
        </Provider>,
      );
    });

    const loginScreen = getByTestId('login-screen');
    expect(loginScreen).toBeTruthy();
  });
});

完整报错详情

FAIL __tests__/login.screen.test.js
  LoginScreen
    ✕ should render the LoginScreen component (5 ms)

  ● LoginScreen › should render the LoginScreen component

    Trying to detect host component names triggered the following error:

    Can't access .root on unmounted test renderer

    There seems to be an issue with your configuration that prevents React Native Testing Library from working correctly.
    Please check if you are using compatible versions of React Native and React Native Testing Library.

       8 |   it('should render the LoginScreen component', async () => {
       9 |     await act(async () => {
    > 10 |       render(
         |             ^
      11 |         <Provider store={store}>
      12 |           <LoginScreen />
      13 |         </Provider>,

      at detectHostComponentNames (node_modules/@testing-library/react-native/src/helpers/host-component-names.tsx:52:11)
      at detectHostComponentNames (node_modules/@testing-library/react-native/src/helpers/host-component-names.tsx:27:30)
      at renderInternal (node_modules/@testing-library/react-native/src/render.tsx:49:40)
      at renderInternal (node_modules/@testing-library/react-native/src/render.tsx:32:10)
      at __tests__/login.screen.test.js:10:13
      at asyncGeneratorStep (node_modules/@babel/runtime/helpers/asyncToGenerator.js:3:24)
      at _next (node_modules/@babel/runtime/helpers/asyncToGenerator.js:22:9)
      at node_modules/@babel/runtime/helpers/asyncToGenerator.js:27:7
      at node_modules/@babel/runtime/helpers/asyncToGenerator.js:19:12
      at callback (node_modules/@testing-library/react-native/src/act.ts:31:24)
      at act (node_modules/react/cjs/react.development.js:2512:16)
      at actImplementation (node_modules/@testing-library/react-native/src/act.ts:30:25)
      at Object.<anonymous> (__tests__/login.screen.test.js:9:14)
      at asyncGeneratorStep (node_modules/@babel/runtime/helpers/asyncToGenerator.js:3:24)
      at _next (node_modules/@babel/runtime/helpers/asyncToGenerator.js:22:9)
      at node_modules/@babel/runtime/helpers/asyncToGenerator.js:27:7
      at Object.<anonymous> (node_modules/@babel/runtime/helpers/asyncToGenerator.js:19:12)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        0.931 s, estimated 1 s
Ran all test suites.

解决方案

1. 移除手动包裹的act调用

react-native-testing-library的render方法已经内置了act的处理逻辑,手动用await act()包裹render会导致组件被提前卸载,触发报错。同时,需从render的返回值中获取查询方法(如getByTestId),避免全局上下文污染。

修改后的测试代码:

import { render, getByTestId } from '@testing-library/react-native';
import { Provider } from 'react-redux';
import LoginScreen from '../path/to/LoginScreen';
import store from '../path/to/store';

describe('LoginScreen', () => {
  it('should render the LoginScreen component', () => {
    // 从render返回值解构查询方法
    const { getByTestId } = render(
      <Provider store={store}>
        <LoginScreen />
      </Provider>,
    );

    const loginScreen = getByTestId('login-screen');
    expect(loginScreen).toBeTruthy();
  });
});

2. 确认依赖版本兼容性

你的当前依赖版本是兼容的:React Native 0.72.x 对应@testing-library/react-native 12.x版本,符合官方兼容要求。如果后续仍有问题,可核对各库的版本兼容矩阵。

3. 检查Redux Store初始化(若涉及异步操作)

如果你的Redux store在初始化时有异步dispatch操作(如请求用户信息),需确保测试前store已完成初始化,或使用mock store模拟状态,避免组件因等待异步状态而出现渲染异常。例如使用redux-mock-store创建模拟store:

import configureMockStore from 'redux-mock-store';

const mockStore = configureMockStore();
const store = mockStore({
  // 模拟初始状态
  auth: { isLoading: false },
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 05:25:35