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

index.spec.tsx 1.2KB

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