Last active
October 14, 2021 16:11
-
-
Save esmevane/edc75a549b03c14771b8847476ab8fb9 to your computer and use it in GitHub Desktop.
[ Typescript / React / Testing Library ]: Going through the create user kata
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { render } from '@testing-library/react'; | |
import userEvents from '@testing-library/user-event'; | |
import { useState } from 'react'; | |
function usePassword() { | |
const [password, setPassword] = useState(''); | |
const [show, setShow] = useState(false); | |
const toggle = () => setShow((previousShowValue) => !previousShowValue); | |
const update = (event: React.ChangeEvent<HTMLInputElement>) => | |
setPassword(event.target.value); | |
return [ | |
{ password, show }, | |
{ toggle, update }, | |
] as const; | |
} | |
function CreateUser() { | |
const [state, events] = usePassword(); | |
return ( | |
<form> | |
<input type="email" placeholder="[email protected]" name="email" /> | |
<input | |
type="password" | |
placeholder="password" | |
name="password" | |
onChange={events.update} | |
value={state.password} | |
/> | |
{state.show ? <div>{state.password}</div> : null} | |
<button type="button" onClick={events.toggle}> | |
{state.show ? 'Hide' : 'Show'} | |
</button> | |
</form> | |
); | |
} | |
describe('Create user form', () => { | |
it('accepts emails', async () => { | |
const form = render(<CreateUser />); | |
const email = await form.findByPlaceholderText('[email protected]'); | |
userEvents.type(email, '[email protected]'); | |
expect(email).toHaveValue('[email protected]'); | |
}); | |
it('accepts passwords', async () => { | |
const form = render(<CreateUser />); | |
const password = await form.findByPlaceholderText('password'); | |
userEvents.type(password, 'super secret password phrase'); | |
expect(password).toHaveValue('super secret password phrase'); | |
}); | |
it('lets me show or hide a password', async () => { | |
const form = render(<CreateUser />); | |
const password = await form.findByPlaceholderText('password'); | |
userEvents.type(password, 'super secret password phrase'); | |
const passwordOutput = form.queryByText('super secret password phrase'); | |
expect(passwordOutput).toBeNull(); | |
userEvents.click(await form.findByText('Show')); | |
await form.findByText('super secret password phrase'); | |
}); | |
xit('creates a user', async () => { | |
return; | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment