Form.spec.tsx 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import { renderHook, act } from '@testing-library/react-hooks';
  2. import { IForm, useFormValidation } from '../Form';
  3. const mockForm: IForm[] = [
  4. {
  5. key: 'username',
  6. value: '',
  7. needCheck: true,
  8. },
  9. {
  10. key: 'nickname',
  11. value: '',
  12. needCheck: false,
  13. },
  14. ];
  15. test('test useFormValidation hook', () => {
  16. const { result } = renderHook(() => useFormValidation(mockForm));
  17. const { checkFormValid, checkIsValid, validation } = result.current;
  18. expect(checkFormValid(mockForm)).toBeFalsy();
  19. expect(Object.keys(validation)).toEqual(['username']);
  20. act(() => {
  21. const { result } = checkIsValid({
  22. value: '',
  23. key: 'username',
  24. rules: [{ rule: 'require', errorText: 'name is required' }],
  25. });
  26. expect(result).toBeTruthy();
  27. });
  28. act(() => {
  29. const { result } = checkIsValid({
  30. value: '11111',
  31. key: 'email',
  32. rules: [{ rule: 'email', errorText: 'email is invalid' }],
  33. });
  34. expect(result).toBeTruthy();
  35. });
  36. act(() => {
  37. const { result } = checkIsValid({
  38. value: '12345678aQ',
  39. key: 'password',
  40. rules: [{ rule: 'password', errorText: 'password is invalid' }],
  41. });
  42. expect(result).toBeTruthy();
  43. });
  44. });