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

RTL导入render报TypeError 无法读取undefined的length属性

报错原因

核心问题出在你的Jest配置中开启了automock: true。
该配置开启后,Jest会自动为所有导入的外部模块生成mock桩,默认所有导出值都是undefined。@testing-library/react的render方法需要调用react-dom、jsdom等依赖的真实实现完成组件挂载,这些依赖被自动mock后,内部逻辑执行时尝试读取某个被置为undefined的数组属性的length值,就会触发你看到的类型错误,和测试用例本身的组件写法没有关系。

修复方案
  • 优先方案:直接删除Jest配置中的automock: true项。绝大多数前端单元测试场景都不需要开启全局自动mock,需要mock特定依赖时,单独在测试文件中调用jest.mock('模块名')定向处理即可,维护成本更低也不容易出现意外mock的问题。
    修复后的配置参考:
import type { Config } from '@jest/types';

const config: Config.InitialOptions = {
    preset: 'ts-jest',
    testEnvironment: 'jsdom',
    verbose: true,
};
export default config;
  • 特殊兼容方案:如果业务场景必须保留全局自动mock,需要在所有用到RTL的测试文件顶部,手动取消RTL及其核心依赖的mock,注意jest.unmock必须写在import语句之前:
jest.unmock('react');
jest.unmock('react-dom');
jest.unmock('@testing-library/react');
import React from 'react';
import { render, screen } from '@testing-library/react';

describe('app component', () => {
    it('renders header', () => {
        const Test = () => <h1>React</h1>;
        render(<Test />);
        screen.getByText(/react/i);
        screen.debug();
    });
});

修改完成后重新执行测试命令,用例即可正常运行通过。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 06:42:37