Skip to content

Commit 47e8029

Browse files
chore: Refactor handleFormError to handle single string error
1 parent f186230 commit 47e8029

2 files changed

Lines changed: 65 additions & 0 deletions

File tree

src/utils/handleFormErrors.test.ts

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
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+
})

src/utils/handleFormErrors.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,11 @@ export const handleFormError = <TField extends string>(
1515
e: BackendErrorResponseType<TField>,
1616
callback: CallbackType<TField>
1717
) => {
18+
if (typeof e === 'string') {
19+
callback({ field: '' as TField, description: e })
20+
return
21+
}
22+
1823
Object.entries(e).forEach(([key, value]) => {
1924
callback({ field: key as TField, description: value as string })
2025
})

0 commit comments

Comments
 (0)