import { render } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import * as React from 'react'
import Login from '../login'
async function setup() {
const handleSubmit = jest.fn()
const utils = await render(<Login onSubmit={handleSubmit} />)
const user = { username: 'michelle', password: 'smith' }
const changeUsernameInput = value =>
userEvent.type(utils.getByLabelText(/username/i), value)
const changePasswordInput = value =>
userEvent.type(utils.getByLabelText(/password/i), value)
const clickSubmit = () => userEvent.click(utils.getByText(/submit/i))
return {
...utils,
handleSubmit,
user,
changeUsernameInput,
changePasswordInput,
clickSubmit,
}
}
async function setupSuccessCase() {
const utils = await setup()
utils.changeUsernameInput(utils.user.username)
utils.changePasswordInput(utils.user.password)
utils.clickSubmit()
return utils
}
async function setupWithNoPassword() {
const utils = await setup()
utils.changeUsernameInput(utils.user.username)
utils.clickSubmit()
const errorMessage = utils.getByRole('alert')
return { ...utils, errorMessage }
}
async function setupWithNoUsername() {
const utils = await setup()
utils.changePasswordInput(utils.user.password)
utils.clickSubmit()
const errorMessage = utils.getByRole('alert')
return { ...utils, errorMessage }
}
test('calls onSubmit with the username and password', async () => {
const { handleSubmit, user } = await setupSuccessCase()
expect(handleSubmit).toHaveBeenCalledTimes(1)
expect(handleSubmit).toHaveBeenCalledWith(user)
})
test('shows an error message when submit is clicked and no username is provided', async () => {
const { handleSubmit, errorMessage } = await setupWithNoUsername()
expect(errorMessage).toHaveTextContent(/username is required/i)
expect(handleSubmit).not.toHaveBeenCalled()
})
test('shows an error message when password is not provided', async () => {
const { handleSubmit, errorMessage } = await setupWithNoPassword()
expect(errorMessage).toHaveTextContent(/password is required/i)
expect(handleSubmit).not.toHaveBeenCalled()
})