Arquivo Sortition.tsx
import { useState } from "react"
import Card from "../components/Card"
import { useListParticipants } from "../state/hook/useListParticipants"
import { useResultSortition } from "../state/hook/useResultSortition"
import './Sortition.css'
const Sortition = () => {
const participants = useListParticipants()
const [participantTurn, setParticipantTurn] = useState('')
let [secretFriend, setSecretFriend] = useState('')
const result = useResultSortition()
const sort = (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault()
if (result.has(participantTurn)) {
setSecretFriend(result.get(participantTurn)!)
// Add Timeout to clear secretFriend after using
setTimeout(() => {
setSecretFriend('')
}, 5000)
}
}
return(
<Card>
<section className="sortition">
<h2>Quem vai tirar o papelzinho?</h2>
<form onSubmit={sort}>
<select
required
name="participantTurn"
id="participantTurn"
placeholder="Selecione o seu nome"
value={participantTurn}
onChange={event => setParticipantTurn(event.target.value)}
>
<option>Selecione seu nome </option>
{participants.map(participant => <option key={participant}>{participant}</option>)}
</select>
<p>Clique em em sortear para ver quem é seu amigo secreto!</p>
<button className="button-sortition">Sortear</button>
</form>
{secretFriend && <p className="result" role="alert">{secretFriend}</p>}
<footer className="sortition">
<img src="imagens/aviao.png" className="plane" alt="Um desenho de um avião de papel" />
</footer>
</section>
</Card>
)
}
export default Sortition
New testcase in Sortition.test.tsx
test('When user request to see secret Friend Then the secret friend is displayed and disapear 5 second later.', () => {
jest.useFakeTimers()
const select = screen.getByPlaceholderText('Selecione o seu nome')
fireEvent.change(select, {
target:{
value: participants[0]
}
})
const button = screen.getByRole('button')
fireEvent.click(button)
let secretFriend = screen.queryByRole('alert')
expect(secretFriend).toBeInTheDocument()
act(() => {
jest.runAllTimers()
})
secretFriend = screen.queryByRole('alert')
expect(secretFriend).not.toBeInTheDocument()
});