clagccs
clagccs

Reputation: 2324

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

Upvotes: 0

Views: 825

Answers (1)

Carsten Codes
Carsten Codes

Reputation: 131

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.

Upvotes: 0

Related Questions