當子元件被模擬時,如何測試父元件中的子元件是否使用正確的 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粉5510842952024-01-17 00:18:16
這就像開玩笑地測試元件道具一樣。我參考了這篇文章作為我的解決方案: 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' }) ) }) })