Simulate React components in Vitest
P粉547420474
P粉547420474 2024-01-16 11:10:45
0
1
524

How to test whether the child component in the parent component is called correctly with the correct props when the child component is mocked. I get the error:

RangeError: Maximum call stack size exceeded

My vitest configuration:

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)

My test code:

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

reply all(1)
P粉551084295

It's like testing component props in jest. I referred this article as my solution: https://robertmarshall.dev/blog/react-component-props-passed-to-child-jest-unit-test/

Since you didn't include the original component, I can't verify the fix. I would try something like this:

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' 
      }) 
    )
  })
})
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template