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

使用React Testing Library测试组件时出现useState读取null属性错误

React Testing Library + Jest 测试时出现无效钩子错误的解决建议

问题描述

使用React Testing Library和Jest测试CounterApp组件时,组件正常渲染无问题,但执行测试时出现TypeError: Cannot read properties of null (reading 'useState')错误。

组件代码

import PropTypes from "prop-types";
import { useState } from "react";

export const CounterApp = ({ value }) => {
    const [counter, setCounter] = useState(value);

    function handleAdd() {
        setCounter(counter + 1);
    }
    function handleSubtract() {
        if (counter > 0) {
            setCounter(counter - 1);
        }
    }

    function handleReset() {
        setCounter(0);
    }
    return (
        <>
            <h1>CounterApp</h1>
            <h2> {counter} </h2>
            <button onClick={handleAdd}>+1</button>
            <button onClick={handleSubtract}>-1</button>
            <button onClick={handleReset}>Reset</button>
        </>
    );
};

CounterApp.propTypes = {
    value: PropTypes.number.isRequired,
};

测试代码

import { render } from "@testing-library/react";
import { CounterApp } from "../../src/components/CounterApp";

describe("<CounterApp /> Tests", () => {
    const initialValue = 10;

    test("should match the snapshot", () => {
        const { container } = render(<CounterApp value={initialValue} />);
        expect(container).toMatchSnapshot();
    });
});

报错信息

● <CounterApp /> Tests › should match the snapshot                  

    TypeError: Cannot read properties of null (reading 'useState')    

      3 |                                                              
      4 | export const CounterApp = ({ value }) => {                  
    > 5 |       const [counter, setCounter] = useState(value);        
        |                                             ^
      6 |
      7 |       function handleAdd() {
      8 |               setCounter(counter + 1);

      at useState (node_modules/react/cjs/react.development.js:1622:21)
      at CounterApp (src/components/CounterApp.jsx:5:40)
      at renderWithHooks (../node_modules/react-dom/cjs/react-dom.development.js:16305:18)
      at mountIndeterminateComponent (../node_modules/react-dom/cjs/react-dom.development.js:20074:13)
      at beginWork (../node_modules/react-dom/cjs/react-dom.development.js:21587:16)
      at beginWork$1 (../node_modules/react-dom/cjs/react-dom.development.js:27426:14)
      at performUnitOfWork (../node_modules/react-dom/cjs/react-dom.development.js:26560:12)
      at workLoopSync (../node_modules/react-dom/cjs/react-dom.development.js:26466:5)
      at renderRootSync (../node_modules/react-dom/cjs/react-dom.development.js:26434:7)
      at recoverFromConcurrentError (../node_modules/react-dom/cjs/react-dom.development.js:25850:20)
      at performConcurrentWorkOnRoot (../node_modules/react-dom/cjs/react-dom.development.js:25750:22)
      at flushActQueue (../node_modules/react/cjs/react.development.js:2667:24)
      at act (../node_modules/react/cjs/react.development.js:2582:11) 
      at ../node_modules/@testing-library/react/dist/act-compat.js:63:25
      at renderRoot (../node_modules/@testing-library/react/dist/pure.js:159:26)
      at render (../node_modules/@testing-library/react/dist/pure.js:246:10)
      at Object.<anonymous> (test/components/CounterApp.test.jsx:8:31)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        2.194 s

解决建议

  • 确保React与React DOM版本一致:检查package.json中react和react-dom的版本号,必须完全匹配。可通过npm list react react-dom查看当前版本,若不一致,执行npm install react@<对应版本号> react-dom@<对应版本号>重新安装匹配版本。
  • 清理依赖缓存并重装:删除node_modules和package-lock.json(或yarn.lock),执行npm install重新安装所有依赖,避免缓存导致的依赖异常。
  • 检查测试环境配置:确认Jest的配置文件(如jest.config.js)中未错误覆盖React的导入路径,确保测试环境使用的是正确的React开发包。
  • 验证组件导入方式:确保测试文件中正确导入了CounterApp组件,路径无错误,避免因组件未正确加载导致的钩子执行异常。

内容的提问来源于stack exchange,提问作者Daniel David Jiménez Paz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 19:56:13