Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

433
Views
La mejor manera de probar un texto en una etiqueta div o p en react-testing-library

¿Cuál es la mejor manera de probar un texto en una etiqueta div o ap en react-testing-library?

Supongamos que tenemos un componente de reacción como tal:

 const Greeting = ({name}) => { return <div>Hello {name}!</div> }

¿Cuál sería la mejor manera de probar que el componente genera el valor esperado, sería usando toBeInTheDocument() :

 import {render, screen} from '@testing-library/react' import Greeting from './greeting' test('it renders the given name in the greeting', () => { render(<Greeting name="John Doe"/>) expect(screen.getByText(`Welcome John Doe!`)).toBeInTheDocument() })

o usando toBeVisible()

 import {render, screen} from '@testing-library/react' import Greeting from './greeting' test('it renders the given name in the greeting', () => { render(<Greeting name="John Doe"/>) expect(screen.getByText(`Welcome John Doe!`)).toBeVisible() })

o ninguno :

 import {render, screen} from '@testing-library/react' import Greeting from './greeting' test('it renders the given name in the greeting', () => { render(<Greeting name="John Doe"/>) screen.getByText(`Welcome John Doe!`) })

El último tiene más sentido para mí como 'Welcome John Doe!' no está en la página, fallará inmediatamente mientras que si está en la página, las dos primeras proposiciones serían equivalentes a: expect(true).toBe(true)

¿Me estoy perdiendo de algo?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

La diferencia entre .toBeInTheDocument() y .toBeVisible() se explica claramente en el documento.

En resumen: un elemento puede estar presente en el documento pero no ser visible para el usuario .

P.ej

 import { render, screen } from '@testing-library/react'; import React from 'react'; import '@testing-library/jest-dom/extend-expect'; function Test() { return <div style={{ display: 'none' }}>test</div>; } describe('toBeVisible-VS-toBeInDocument', () => { test('should pass', () => { render(<Test />); expect(screen.getByText(/test/)).not.toBeVisible(); expect(screen.getByText(/test/)).toBeInTheDocument(); }); });

Resultado de la prueba:

 PASS examples/toBeVisible-VS-toBeInDocument/index.test.tsx (8.595 s) toBeVisible-VS-toBeInDocument ✓ should pass (49 ms) Test Suites: 1 passed, 1 total Tests: 1 passed, 1 total Snapshots: 0 total Time: 9.099 s, estimated 10 s

obtener * o consulta *?

La única razón por la que se expone la variante query* de las consultas es para que tenga una función a la que pueda llamar que no arroje un error si no se encuentra ningún elemento que coincida con la consulta (devuelve nulo si no se encuentra ningún elemento). La única razón por la que esto es útil es para verificar que un elemento no se represente en la página. La razón por la que esto es tan importante es porque las variantes get* y find* arrojarán un error extremadamente útil si no se encuentra ningún elemento: imprime el documento completo para que pueda ver lo que se representa y tal vez por qué su consulta no pudo encontrar lo que estaba. buscando. Mientras que query* solo devolverá nulo y lo mejor que puede hacer toBeInTheDocument es decir: "null no está en el documento", lo cual no es muy útil.

En resumen: solo use las variantes de query* para afirmar que no se puede encontrar un elemento.

get* query es la mejor manera de verificar si un elemento está presente en el documento.

De la publicación Uso de variantes get* como aserciones .

Consejo: si quieres afirmar que algo existe, haz esa afirmación explícita.

Aparte del punto en el artículo, creo que sería mucho más legible.

Asi que:

 // You can do this screen.getByText(`Welcome John Doe!`); // better, much more readable expect(screen.getByText(`Welcome John Doe!`)).toBeInTheDocument();
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!