搜索

首页  >  问答  >  正文

Vitest中模拟React组件

当子组件被模拟时,如何测试父组件中的子组件是否使用正确的 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粉547420474P粉547420474313 天前527

全部回复(1)我来回复

  • P粉551084295

    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' 
          }) 
        )
      })
    })

    回复
    0
  • 取消回复