Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

119
Vistas
Check if object contains a link in React Testing Library

Having the following unit test:

  const MY_URL = 'example.com'
  it('should render MyComponent with url', () => {
    const { getByTestId } = render(<MyComponent />);
    const myLink = getByTestId(TestIds.LINK);
    expect(loggingLink).toContain(MY_URL);
  });

The test fails with the following message:

 Expected value:  "example.com"
 Received object: <div class="m-3" data-testid="test-link"><a href="example.com">my-link</a></div>

So it seems that toContain doesn't check what is inside of that object. Is there a method to check that the URL is inside the object?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You can get the anchor element with ByRole query. Just search it with link and then check the attribute href:

// I used screen in this case, but you can get getByRole from render.
const anchorElement = screen.getByRole('link');

expect(anchorElement).toBeInTheDocument();

expect(anchorElement).toHaveAttribute('href', 'example.com');

Anchor elements have link role only when href attribute is present, otherwise no corresponding role. You can check more about it here.

about 4 years ago · Juan Pablo Isaza Denunciar

0

There's a couple of things. First, toContain is for testing if an element exists in an array. https://jestjs.io/docs/expect#tocontainitem

Second, the point of RTL is not to test properties and such, but to test what users see on the screen. So I guess the "RTL way" of doing this would be to click the link and see what's displayed. Which admittedly is not always helpful in every situation!

If you are absolutely sure this url needs a test around it, then you do have an escape hatch via the underlying jest jsdom selectors. You can query an element using a bog standard querySelector and then test the href property directly.

In fact you don't even need querySelector. The getBy methods all return a jsdom object which you can then test with getAttribute('href')

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda