Skip to content

Instantly share code, notes, and snippets.

@juanpablocs
Last active September 15, 2021 17:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juanpablocs/cae9d36957a2e1bfae01219ff0c148cd to your computer and use it in GitHub Desktop.
Save juanpablocs/cae9d36957a2e1bfae01219ff0c148cd to your computer and use it in GitHub Desktop.
React testing Library and jest tips and tricks

Jest and React testing library

Funciones globales para ejecutar pruebas describe(name, cb) te permite agrupar varios test unitarios y dentro podemos usar it(name, cb) o test(name, cb) para acceder a un elemento screen y para debugear screen.debug()

usamos render de @testing-library/react para pintar y evaluar el componente.

para acceder al dom del componente usamos screen y buscar elementos con getBy... y con promise findBy...

los objetos y funciones mas usados

import { render, screen, fireEvent } from '@testing-library/react';

// order 1
render(<Component />);
// order 2
screen.getByLabelText('Texto') // or (/texto/i)
fireEvent.click(screen.getBy...) //fireEvent.mouseover etc
// order 3
expect().toBe..
import React from 'react';
import { render, screen, fireEvent } from '@testing-library/react';
import { SectionProduct } from './SectionProduct';

describe('SectionProduct Component', () => {
  it('should render name section', () => {
    render(<SectionProduct name="Milanesa" products={[]} />);
    expect(screen.getByText('Milanesa')).toBeInTheDocument();
  });
  it('should expanded products when click to section', () => {
    render(<SectionProduct name="Milanesa" products={[]} />);
    fireEvent.click(screen.getByRole('listitem'));
    expect(screen.getByLabelText('collapsed')).toBeInTheDocument();
  });
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment