|
| 1 | +import { handleFormError } from './handleFormErrors' |
| 2 | + |
| 3 | +console.error = () => {} |
| 4 | + |
| 5 | +describe('handleFormError', () => { |
| 6 | + it('should call the callback function for each error field', () => { |
| 7 | + const error = { |
| 8 | + username: 'Username is required', |
| 9 | + password: 'Password is required', |
| 10 | + } |
| 11 | + |
| 12 | + const callback = jest.fn() |
| 13 | + |
| 14 | + handleFormError(error, callback) |
| 15 | + |
| 16 | + expect(callback).toHaveBeenCalledTimes(2) |
| 17 | + expect(callback).toHaveBeenCalledWith({ |
| 18 | + field: 'username', |
| 19 | + description: 'Username is required', |
| 20 | + }) |
| 21 | + expect(callback).toHaveBeenCalledWith({ |
| 22 | + field: 'password', |
| 23 | + description: 'Password is required', |
| 24 | + }) |
| 25 | + }) |
| 26 | + |
| 27 | + it('should call the callback function with the correct field and description', () => { |
| 28 | + const error = { |
| 29 | + email: 'Email is invalid', |
| 30 | + } |
| 31 | + |
| 32 | + const callback = jest.fn() |
| 33 | + |
| 34 | + handleFormError(error, callback) |
| 35 | + |
| 36 | + expect(callback).toHaveBeenCalledTimes(1) |
| 37 | + expect(callback).toHaveBeenCalledWith({ field: 'email', description: 'Email is invalid' }) |
| 38 | + }) |
| 39 | + |
| 40 | + it('should handle a single string error', () => { |
| 41 | + const error = 'Internal server error' |
| 42 | + |
| 43 | + const callback = jest.fn() |
| 44 | + |
| 45 | + handleFormError(error, callback) |
| 46 | + |
| 47 | + expect(callback).toHaveBeenCalledTimes(1) |
| 48 | + expect(callback).toHaveBeenCalledWith({ field: '', description: 'Internal server error' }) |
| 49 | + }) |
| 50 | + |
| 51 | + it('should not call the callback function if the error is empty', () => { |
| 52 | + const error = {} |
| 53 | + |
| 54 | + const callback = jest.fn() |
| 55 | + |
| 56 | + handleFormError(error, callback) |
| 57 | + |
| 58 | + expect(callback).not.toHaveBeenCalled() |
| 59 | + }) |
| 60 | +}) |
0 commit comments