Skip to content

Instantly share code, notes, and snippets.

@webpapaya
Last active October 20, 2020 09:24
Show Gist options
  • Save webpapaya/f2912dd7f62462e8ca87c2241b95a8fc to your computer and use it in GitHub Desktop.
Save webpapaya/f2912dd7f62462e8ca87c2241b95a8fc to your computer and use it in GitHub Desktop.
const SignInForm = ({ onSubmit }) => {
const [formState, setFormState] = useState({ username: '', password: '' })
const handleChange = (evt) => {
setFormState({ ...formState, [evt.target.name]: evt.target.value })
}
return (
<form onSubmit={() => onSubmit(formState)}>
<input
name="username"
onChange={handleChange}
value={formState.username}
/>
<input
name="password"
onChange={handleChange}
value={formState.password}
/>
</form>
)
}
describe('SignInForm', () => {
it('contains input for username', () => {
const { container } = render(<SignInForm />)
expect(container.querySelector('[name="username"]')).toBeTruthy()
})
it('contains input for password', () => {
const { container } = render(<SignInForm />)
expect(container.querySelector('[name="password"]')).toBeTruthy()
})
it('calls onSubmit function when submitted', () => {
const onSubmit = jest.fn()
const { container } = render(<SignInForm onSubmit={onSubmit} />)
fireEvent.submit(container.querySelector('form'))
expect(onSubmit).toHaveBeenLastCalledWith({ username: '', password: '' })
})
it('WHEN username was filled, reports username in submit call', () => {
const onSubmit = jest.fn()
const username = 'sepp'
const { container } = render(<SignInForm onSubmit={onSubmit} />)
fireEvent.change(container.querySelector('[name="username"]'), { target: { value: username, name: 'username' }})
fireEvent.submit(container.querySelector('form'))
expect(onSubmit).toHaveBeenLastCalledWith({ username, password: '' })
})
it('WHEN password was filled, reports password in submit call', () => {
const onSubmit = jest.fn()
const password = 'sepp'
const { container } = render(<SignInForm onSubmit={onSubmit} />)
fireEvent.change(container.querySelector('[name="password"]'), { target: { value: password, name: 'password' }})
fireEvent.submit(container.querySelector('form'))
expect(onSubmit).toHaveBeenLastCalledWith({ username: '', password })
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment