Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit e1e12d8

Browse files
committed
Add unit tests
1 parent 73df2da commit e1e12d8

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
import { FormikContextType } from 'formik/dist/types'
2+
import { getFormHelpers, onChangeTrimmed } from './index'
3+
4+
interface TestType {
5+
untouchedGoodField: string
6+
untouchedBadField: string
7+
touchedGoodField: string
8+
touchedBadField: string
9+
}
10+
11+
const mockHandleChange = jest.fn()
12+
13+
const form = {
14+
errors: {
15+
untouchedGoodField: undefined,
16+
untouchedBadField: "oops!",
17+
touchedGoodField: undefined,
18+
touchedBadField: 'oops!',
19+
},
20+
touched: {
21+
untouchedGoodField: false,
22+
untouchedBadField: false,
23+
touchedGoodField: true,
24+
touchedBadField: true,
25+
},
26+
handleChange: mockHandleChange,
27+
handleBlur: jest.fn(),
28+
getFieldProps: (name: string) => {
29+
return {
30+
name,
31+
onBlur: jest.fn(),
32+
onChange: jest.fn(),
33+
value: ''
34+
}
35+
}
36+
} as unknown as FormikContextType<TestType>
37+
38+
describe("form util functions", () => {
39+
describe("getFormHelpers", () => {
40+
const untouchedGoodResult = getFormHelpers<TestType>(form, "untouchedGoodField")
41+
const untouchedBadResult = getFormHelpers<TestType>(form, "untouchedBadField")
42+
const touchedGoodResult = getFormHelpers<TestType>(form, "touchedGoodField")
43+
const touchedBadResult = getFormHelpers<TestType>(form, "touchedBadField")
44+
it("populates the 'field props'", () => {
45+
expect(untouchedGoodResult.name).toEqual("untouchedGoodField")
46+
expect(untouchedGoodResult.onBlur).toBeDefined()
47+
expect(untouchedGoodResult.onChange).toBeDefined()
48+
expect(untouchedGoodResult.value).toBeDefined()
49+
})
50+
it("sets the id to the name", () => {
51+
expect(untouchedGoodResult.id).toEqual("untouchedGoodField")
52+
})
53+
it("sets error to true if touched and invalid", () => {
54+
expect(untouchedGoodResult.error).toBeFalsy
55+
expect(untouchedBadResult.error).toBeFalsy
56+
expect(touchedGoodResult.error).toBeFalsy
57+
expect(touchedBadResult.error).toBeTruthy
58+
})
59+
it("sets helperText to the error message if touched and invalid", () => {
60+
expect(untouchedGoodResult.helperText).toBeUndefined
61+
expect(untouchedBadResult.helperText).toBeUndefined
62+
expect(touchedGoodResult.helperText).toBeUndefined
63+
expect(touchedBadResult.helperText).toEqual("oops!")
64+
})
65+
})
66+
67+
describe("onChangeTrimmed", () => {
68+
it("calls handleChange with trimmed value", () => {
69+
const event = { target: { value: " hello "}} as React.ChangeEvent<HTMLInputElement>
70+
onChangeTrimmed<TestType>(form)(event)
71+
expect(mockHandleChange).toHaveBeenCalledWith({ target: { value: "hello" } })
72+
})
73+
})
74+
})

0 commit comments

Comments
 (0)