DEV Community

Vitor Rios
Vitor Rios

Posted on

2

Entendendo as Nomenclaturas getBy..., findBy... e queryBy... no Jest

No contexto de testes com Jest, especialmente ao testar componentes React usando @testing-library/react, você pode encontrar várias funções de consulta com diferentes prefixos, como getBy..., findBy... e queryBy.... Cada uma dessas funções serve a um propósito específico e entender suas diferenças pode ajudar a escrever testes mais eficazes e robustos.

getBy...

Uso

A função getBy... é usada para selecionar elementos que devem estar presentes no DOM.

Comportamento

Se o elemento não for encontrado, getBy... lança um erro imediatamente. Isso é útil quando você espera que o elemento esteja no DOM após a renderização inicial.

Exemplos

const button = screen.getByText('Submit');
const input = screen.getByPlaceholderText('Enter your name');
Enter fullscreen mode Exit fullscreen mode

Quando Usar

Use getBy... quando você espera que o elemento esteja no DOM imediatamente após a renderização inicial do componente.

Exemplo de Teste com getBy...

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

test('renders submit button', () => {
  render(<MyComponent />);
  const button = screen.getByText('Submit');
  expect(button).toBeInTheDocument();
});
Enter fullscreen mode Exit fullscreen mode

findBy...

Uso

A função findBy... é usada para selecionar elementos que podem aparecer no DOM de forma assíncrona.

Comportamento

Retorna uma Promise que é resolvida quando o elemento é encontrado. Se o elemento não for encontrado dentro de um tempo padrão (1 segundo), a Promise é rejeitada.

Exemplos

const button = await screen.findByText('Submit');
const input = await screen.findByPlaceholderText('Enter your name');
Enter fullscreen mode Exit fullscreen mode

Quando Usar

Use findBy... quando o elemento pode não estar presente imediatamente e pode aparecer depois de alguma operação assíncrona, como uma chamada de API ou uma animação.

Exemplo de Teste com findBy...

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

test('renders submit button asynchronously', async () => {
  render(<MyComponent />);
  const button = await screen.findByText('Submit');
  expect(button).toBeInTheDocument();
});
Enter fullscreen mode Exit fullscreen mode

queryBy...

Uso

A função queryBy... é usada para selecionar elementos que podem ou não estar presentes no DOM.

Comportamento

Retorna null se o elemento não for encontrado, ao invés de lançar um erro.

Exemplos

const button = screen.queryByText('Submit');
const input = screen.queryByPlaceholderText('Enter your name');
Enter fullscreen mode Exit fullscreen mode

Quando Usar

Use queryBy... quando você quer verificar a ausência de um elemento no DOM. É útil para testar condições negativas.

Exemplo de Teste com queryBy...

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

test('does not render submit button initially', () => {
  render(<MyComponent />);
  const button = screen.queryByText('Submit');
  expect(button).not.toBeInTheDocument();
});
Enter fullscreen mode Exit fullscreen mode

Conclusão

A escolha entre getBy..., findBy... e queryBy... depende do comportamento esperado do componente que você está testando. Usar a função adequada pode tornar seus testes mais robustos e claros, além de evitar falsos positivos ou falhas desnecessárias. Compreender essas diferenças é crucial para escrever testes eficazes e manter a qualidade do seu código.

Agora que você entende como essas funções de consulta funcionam, pode aplicá-las corretamente em seus testes, garantindo que seus componentes React sejam testados de forma abrangente e eficiente.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay