Heim > Fragen und Antworten > Hauptteil
So testen Sie, ob die untergeordnete Komponente in der übergeordneten Komponente korrekt mit den richtigen Requisiten aufgerufen wird, wenn die untergeordnete Komponente verspottet wird. Ich erhalte die Fehlermeldung:
RangeError: Maximum call stack size exceeded
Meine vitest-Konfiguration:
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)
Mein Testcode:
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' }) ) }) })