List testing in React

Asked

Viewed 26 times

0

I need to create a test to test a list (li) in Reactjs, the list is rendered after clicking the send button. My code:

import React, { useState } from 'react'

import Button from '../../components/button/Button'
import './AlunoTurma.css'

const turmas = [
  {
    id: 1,
    turma: 'Matutino',
  },
  {
    id: 2,
    turma: 'Vespertino',
  },
  {
    id: 3,
    turma: 'Noturno',
  },
]
const alunos = [
  {
    matricula: 10000,
    nome: 'João',
    endereco: 'Rua A',
  },
  {
    matricula: 10001,
    nome: 'José',
    endereco: 'Rua B',
  },
  {
    matricula: 10002,
    nome: 'Pedro',
    endereco: 'Rua C',
  },
  {
    matricula: 10003,
    nome: 'Laura',
    endereco: 'Rua D',
  },
  {
    matricula: 10004,
    nome: 'Luciana',
    endereco: 'Rua E',
  },
]

function AlunoTurma() {
  const [infoTurma, setInfoTurma] = useState('')
  const [infoAluno, setInfoAluno] = useState('')
  const [values, setValues] = useState([])

  function handleSubmit(event) {
    event.preventDefault()
    if (infoTurma.trim() || infoAluno.trim()) {
      setValues([...values, { turma: infoTurma, aluno: infoAluno }])

      clearSelect()
    }
  }
  console.log(values)
  function clearSelect() {
    setInfoTurma('')
    setInfoAluno('')
  }


  return (
    <div className="form-aluno">
      <h1>Formulário de cadastro de Turmas</h1>
      <form onSubmit={handleSubmit}>
        <label htmlFor="">Selecione a Turma</label>
        <select
          className="select-form"
          value={infoTurma}
          onChange={(e) => setInfoTurma(e.target.value)}
          data-testid="select-turma"
        >
          <option value="0">Selecione uma Turma</option>
          {turmas.map((item) => (
            <option value={item.turma} key={item.id} data-testid="form-turma">
              {item.turma}
            </option>
          ))}
        </select>
        <label htmlFor="">Selecione o Aluno</label>
        <select
          className="select-form"
          value={infoAluno}
          onChange={(e) => setInfoAluno(e.target.value)}
          data-testid="select-aluno"
        >
          <option value="0">Selecione um Aluno</option>
          {alunos.map((aluno) => (
            <option
              value={aluno.nome}
              key={aluno.matricula}
              data-testid="form-aluno"
            >
              {aluno.nome}
            </option>
          ))}
        </select>
        <Button text="Cadastra Aluno" />
      </form>

      <div className="list-container">
        <ul>
          {values.map((item, index) => (
            <li key={index} data-testid="todo-list">
              <div className="list-turma">
                <span>{item.turma}</span>
                <p>{item.aluno}</p>
              </div>
            </li>
          ))}
        </ul>
      </div>
    </div>
  )
}

export default AlunoTurma

My test:

import React from 'react'
import { render, fireEvent, waitFor } from '@testing-library/react'

import AlunoTurma from './AlunoTurma'

describe('Teste selecão de Turmas e Alunos', () => {
  it('Simula a seleção para turma', async () => {
    const { getByTestId, getAllByTestId } = render(<AlunoTurma />)
    fireEvent.change(getByTestId('select-turma'), { target: { value: 2 } })
    const optionsTurma = getAllByTestId('form-turma')

    expect(optionsTurma[0].selected).toBeFalsy()
    expect(optionsTurma[1].selected).toBeFalsy()
    expect(optionsTurma[2].selected).toBeFalsy()
  })

  it('Simula a seleção para aluno', async () => {
    const { getByTestId, getAllByTestId } = render(<AlunoTurma />)
    fireEvent.change(getByTestId('select-aluno'), {
      target: { value: 3 },
    })
    const optionsAluno = getAllByTestId('form-aluno')

    expect(optionsAluno[0].selected).toBeFalsy()
    expect(optionsAluno[1].selected).toBeFalsy()
    expect(optionsAluno[2].selected).toBeFalsy()
    expect(optionsAluno[3].selected).toBeFalsy()
    expect(optionsAluno[4].selected).toBeFalsy()

    const btnNode = await waitFor(() => getByTestId('form-btn'))

    fireEvent.click(btnNode)

    const listElement = screen.getByRole('list')
    const listItems = screen.getAllByRole('listitem')

    expect(listElement).toBeInTheDocument()
    expect(listElement).toHaveClass('animals')
    expect(listItems.length).toEqual(5)
  })
})

But accuse this error: Testinglibraryelementerror: Unable to find an accessible element with the role "listitem"

  • Emerson, it’s possible that when you click on the trigger the button-clicking event isn’t quite as synchronous. Import the debug from the React Testing Library and put it right after the event and see if the elements are in the DOM.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.