您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

index.spec.tsx 1.2KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import { render, screen } from '@testing-library/react'
  2. import '@testing-library/jest-dom'
  3. import { z } from 'zod'
  4. import withValidation from '.'
  5. describe('withValidation HOC', () => {
  6. // schema for validation
  7. const schema = z.object({ name: z.string() })
  8. type Props = z.infer<typeof schema> & {
  9. age: number
  10. }
  11. const TestComponent = ({ name, age }: Props) => (
  12. <div>{name} - {age}</div>
  13. )
  14. const WrappedComponent = withValidation(TestComponent, schema)
  15. beforeAll(() => {
  16. jest.spyOn(console, 'error').mockImplementation(() => { })
  17. })
  18. afterAll(() => {
  19. jest.restoreAllMocks()
  20. })
  21. it('renders the component when validation passes', () => {
  22. render(<WrappedComponent name='Valid Name' age={30} />)
  23. expect(screen.getByText('Valid Name - 30')).toBeInTheDocument()
  24. })
  25. it('renders the component when props is invalid but not in schema ', () => {
  26. render(<WrappedComponent name='Valid Name' age={'aaa' as any} />)
  27. expect(screen.getByText('Valid Name - aaa')).toBeInTheDocument()
  28. })
  29. it('does not render the component when validation fails', () => {
  30. render(<WrappedComponent name={123 as any} age={30} />)
  31. expect(screen.queryByText('123 - 30')).toBeNull()
  32. })
  33. })