Skip to content

Latest commit

 

History

History
85 lines (72 loc) · 2.03 KB

example-formik.md

File metadata and controls

85 lines (72 loc) · 2.03 KB
idtitle
example-react-formik
Formik

Example based in this Async Submission Formik example

// myForm.jsimportReactfrom'react'import{Formik,Field,Form}from'formik'constsleep=ms=>newPromise(r=>setTimeout(r,ms))exportconstMyForm=({onSubmit})=>{consthandleSubmit=asyncvalues=>{awaitsleep(500)onSubmit(values)}return(<div><h1>Sign Up</h1><FormikinitialValues={{firstName: '',lastName: '',email: '',}}onSubmit={handleSubmit}><Form><labelhtmlFor="firstName">First Name</label><Fieldid="firstName"name="firstName"placeholder="Jane"/><labelhtmlFor="lastName">Last Name</label><Fieldid="lastName"name="lastName"placeholder="Doe"/><labelhtmlFor="email">Email</label><Fieldid="email"name="email"placeholder="jane@acme.com"type="email"/><buttontype="submit">Submit</button></Form></Formik></div>)}
// myForm.test.jsimportReactfrom'react'import{render,screen,waitFor}from'@testing-library/react'importuserEventfrom'@testing-library/user-event'import{MyForm}from'./myForm.js'test('rendering and submitting a basic Formik form',async()=>{consthandleSubmit=jest.fn()render(<MyFormonSubmit={handleSubmit}/>)constuser=userEvent.setup()awaituser.type(screen.getByRole('textbox',{name: /firstname/i}),'John')awaituser.type(screen.getByRole('textbox',{name: /lastname/i}),'Dee')awaituser.type(screen.getByRole('textbox',{name: /email/i}),'john.dee@someemail.com',)awaituser.click(screen.getByRole('button',{name: /submit/i}))awaitwaitFor(()=>expect(handleSubmit).toHaveBeenCalledWith({email: 'john.dee@someemail.com',firstName: 'John',lastName: 'Dee',}),)})
close