Home  >  Q&A  >  body text

Simulate React components in Vitest

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粉547420474P粉547420474300 days ago514

reply all(1)I'll reply

  • P粉551084295

    P粉5510842952024-01-17 00:18:16

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

    reply
    0
  • Cancelreply