admin管理员组

文章数量:1336208

I'm trying to test with vitest a page with zustand

But i'm getting this error :

TypeError: Cannot read properties of null (reading 'useRef')
 ❯ useRef ../../../../../../node_modules/react/cjs/react.development.js:1630:21
 ❯ useSyncExternalStoreWithSelector ../../../../../../node_modules/use-sync-external-store/cjs/use-sync-external-store-shim/with-selector.development.js:51:17
 ❯ useStore ../../../../../../../coucou/app%20copie2/node_modules/zustand/esm/index.mjs:17:17
 ❯ Module.useBoundStore ../../../../../../../coucou/%20copie2/node_modules/zustand/esm/index.mjs:34:51
 ❯ SaleDetailLayout ../../layout/SaleDetail.layout.tsx:9:20
      7| 
      8| export const SaleDetailLayout = () => {
      9|     const loaded = usePayloadStore((state) => state.loaded)

My vitest config

import { defineConfig } from 'vitest/config'
import react from '@vitejs/plugin-react'
import path, { resolve } from 'path'
import svgr from 'vite-plugin-svgr'

import { fileURLToPath } from 'node:url'
const rootDir = fileURLToPath(new URL('.', import.meta.url))

// /config/
export default defineConfig({
    plugins: [react(), svgr()],
    resolve: {
        alias: {
            '@': path.resolve(__dirname, './src'),
        },
    },
    test: {
        include: ['**/*.test.tsx', '**/*.test.ts'],
        environment: 'happy-dom',
        css: true,
        setupFiles: resolve(rootDir, './test-setup.ts'),
        globals: true,
    },
})

The component

import { usePayloadStore } from '../store/usePayloadStore'

export const SaleDetailLayout = () => {
    const loaded = usePayloadStore((state) => state.loaded)

    return <div>{loaded}</div>
}

The store :

import { create } from 'zustand'

export type PayloadState<T> = {
    payload: T | undefined
    loaded: boolean
    setPayload: (payload: Partial<T>) => void
}

type Payload = {
    saleID?: number
}

export const usePayloadStore = create<PayloadState<Payload>>((set: (payload: object) => void) => ({
    payload: undefined,
    loaded: false,
    setPayload: (payload: Partial<Payload>) => set(() => ({ loaded: true, payload: payload })),
}))

And the test

it("display date", async () => {
    render(<SaleDetailLayout />)

    expect(await screen.findByText(/à 00:00/)).toBeInTheDocument()
})

It's related to zustand, because if I use an other state management lib, I don't get the error (ex. with jotai)

本文标签: Vitest and zustand Cannot read properties of null (reading 39useRef39)Stack Overflow