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

250
Vistas
React Testing Library can't find my self-closing tag in a react fragment, and just renders <body/>

I've got a component like this:

const MyComponent = ({ foo }) => (
  <>
    <div>
    <Header />
      {foo}
    </div>
    <div data-testid="self-closing-tag" className={styles.break} />
  </>
)

(n.b. React should handle the div being a self-closing tag, whereas without react that's not valid html)

I've written a test that renders my component <div data-testid="foo" /> for the foo prop and runs expect(screen.getByTestId('foo')).toBeInTheDocument(); which passes. If I use screen.debug in that test, I get the fully rendered DOM.

But when I write a test for the self closing tag, like so: expect(screen.getByTestId('self-closing-tag')).toHaveClass('break'); I get:

Unable to get element by: [data-testid="self-closing-tag"]

and where I'd expect it to print out the fully rendered DOM, it just prints <body />.

If I put the expect assertion for the self-closing tag in the test for 'foo', they both pass.

describe('<My Component />', () => {
  beforeEach(<MyComponent foo={<div data-testid="foo" />} />);
  it('renders foo', () => {
    expect(screen.getByTestId('foo')).toBeInTheDocument();
    // expect(screen.getByTestId('self-closing-tag')).toHaveClass('break'); -- this passes if uncommmented!
  };
  it('renders the self closing tag', () => {
    expect(screen.getByTestId('self-closing-tag')).toHaveClass('break'); // cannot find element, prints '<body />' as the DOM.
  })
})

I can obviously shove everything in the same it statement, but I'd rather not if possible. I'd also like to understand whats going on.

What have I done wrong?

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

0

That´s because toHaveClass expects an arg with the class name, you can check the docs here.

So, your test could be:

expect(screen.getByTestId("self-closing-tag")).toHaveClass("XX class name you expect XX");

or if you just want to check if the element has the attribute class

expect(screen.getByTestId("self-closing-tag")).toHaveAttribute("class");
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