Vitest and react testing library error testing component with useState: TypeError: Cannot read properties of null (reading ‘useState’)

I’m following some videos about how setup vitest and testing library in my vite project…basically I’ve installed the dependencies in my package.json

"devDependencies": {
        "@testing-library/react": "^16.0.1",
        "@types/react": "^18.3.3",
        "@vitejs/plugin-react": "^4.3.1",
        "globals": "^15.9.0",
        "jsdom": "^25.0.0",
        "vite": "^5.4.1",
        "vitest": "^2.1.1"
    }

updated my vite config

/// <reference types="vite/client" />
/// <reference types="vitest" />

import path from 'node:path'
import react from '@vitejs/plugin-react'
import { defineConfig } from 'vitest/config'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    react({
      jsxImportSource: '@emotion/react',
      babel: {
        plugins: ['@emotion/babel-plugin'],
      },
    }),
  ],
  test: {
    globals: true,
    environment: 'jsdom',
    css: true,
  },
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src'),
      '@components': path.resolve(__dirname, './src/components'),
    },
  },
})

and added this types to my tsconfig.json

"compilerOptions": {
    "paths": {
        "@components/*": ["./src/components/*"],
        "@/*": ["./src/*"]
    },
    "jsxImportSource": "@emotion/react",
    "types": [
        "@emotion/react/types/css-prop",
        "reflect-metadata",
        "jest",
        "vitest/globals",
        "@testing-library/jest-dom"
    ],
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx",
    "allowUmdGlobalAccess": true
},

so far so good…now I write some simple tests

import { useState } from 'react'


console.log('React version:', React.version);
console.log('useState available:', typeof React.useState);

export const ComponentWithState = () => {
  const [counter, setCounter] = useState(0)

  return <div>
    Counter: {counter}
     
    <button type="button" onClick={() => setCounter(counter + 1)}>Increment</button>
  </div>
}

and my test in the same folder

import { fireEvent, render, screen } from '@testing-library/react'
import {ComponentWithState} from './ComponentWithState'

console.log('Test file: React version:', React.version);
console.log('Test file: useState available:', typeof React.useState);

describe('tests', () => {
  it('should be true', () => {
    expect(true).toBe(true)
  })

  it('should render', () => {
    render(<div>Hello</div>)
    expect(screen.getByText('Hello')).toBeDefined()
  })

  it('should increment in ComponentWithState', () => {
    render(<ComponentWithState />)
    expect(screen.getByText('Counter: 0')).toBeDefined()
    fireEvent.click(screen.getByText('Increment'))
    expect(screen.getByText('Counter: 1')).toBeDefined()
  })
})

first two tests passed but should increment in ComponentWithState fails

the error is this

Warning: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
Warning: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.


Error: Uncaught [TypeError: Cannot read properties of null (reading 'useState')]
at reportException (/<my path>/node_modules/jsdom/lib/jsdom/living/helpers/runtime-script-errors.js:66:24)

but seems that useState is not null, is a function according to the logs

React version: 18.3.1
useState available: function
Test file: React version: 18.3.1
Test file: useState available: function

I check some tutorials and these used useState with react testing library without any problem, not sure why I get this error.

any help will be appreciated
thank you so much

Did you already checked the Link from your error message?

There are three common reasons you might be seeing it:

  1. You might be breaking the Rules of Hooks.

  2. You might have mismatching versions of React and React DOM.

  3. You might have more than one copy of React in the same app.

Number 1 does not seem to be the case.

For number 2:

You can run npm ls react-dom […] in your application folder to check which version you’re using.

For number 3:

You can run npm ls react in your application folder to check which version you’re using.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật