Vitest中模拟React组件
P粉547420474
P粉547420474 2024-01-16 11:10:45
0
1
572

当子组件被模拟时,如何测试父组件中的子组件是否使用正确的 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' 
      }) 
    )
  })
})
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板