Vitest中模擬React元件
P粉547420474
P粉547420474 2024-01-16 11:10:45
0
1
521

當子元件被模擬時,如何測試父元件中的子元件是否使用正確的 props 正確呼叫。我收到錯誤:

RangeError: Maximum call stack size exceeded

我的 vitest 設定:

import svgr from 'vite-plugin-svgr'
import { defineConfig } from 'vitest/config'
import type { UserConfig } from 'vitest/config'

import { resolve } from 'path'

export default defineConfig({
  test: {
    environment: 'jsdom',
    setupFiles: ['./tests/setup.ts'],
    environmentMatchGlobs: [['./src/**/*.tsx', 'jsdom']],
    globals: true,
  },
  resolve: {
    alias: [{ find: '@', replacement: resolve(__dirname, './src') }],
  },
  plugins: [svgr()],
} as UserConfig)

我的測試程式碼:

import { render, screen } from '@testing-library/react'
import { vi } from 'vitest'
import Input from '@/components/Input/Input'

import Login from './Login'

vi.mock('@/components/Input/Input', () => ({
  default: vi.fn(),
}))

describe('ConfirmEmail', () => {
  it('renders correctly', () => {
    render(<Login />)

    expect(screen.getByRole('heading', { name: /Login to your account/i }))

    expect(Input).toHaveBeenCalledWith({
      label: 'email',
    }) //error: RangeError: Maximum call stack size exceeded
  })
})


#
P粉547420474
P粉547420474

全部回覆(1)
P粉551084295

這就像開玩笑地測試元件道具一樣。我參考了這篇文章作為我的解決方案: https ://robertmarshall.dev/blog/react-component-props-passed-to-child-jest-unit-test/

################################################################### ###由於您沒有包含原始元件,因此我無法驗證該修復。我會嘗試這樣的事情:###
const mockInput = vi.fn() 
vi.mock('@/components/Input/Input', () => ({ 
  default: (props) => {
    mockInput(props)
    return <div>Input</div>
  }, 
})) 

describe('Confirm Email', () => {
  it('renders correctly', () => {
    render(<Login />) 
   
    expect(screen.getByRole('heading', { name: /Login to your account/i })) 
   
    expect(mock Input).toHaveBeenCalledWith( 
      expect.objectContaining({
        label: 'email' 
      }) 
    )
  })
})
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板