Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between `container` and `container.firstChild` in RTL

When I do snapshot testing, for example, what is the difference if I write in this way:

it('Should render correctly', () => {
  const { container } = render<MyComponent />; 
  expect(container).toMatchSnapshot();
})

vs when I specify container.firstChild

it('Should render correctly', () => {
  const { container } = render<MyComponent />; 
  expect(container.firstChild).toMatchSnapshot();
})

I couldn't google any answers on this.

like image 454
Samat Zhetibaev Avatar asked Sep 06 '25 07:09

Samat Zhetibaev


1 Answers

container is a new div element appended into baseElement element. The default baseElement is document.body. To get the root element of your rendered component, use container.firstChild.

You can found it from the source code of the render function.

// ...
if (!baseElement) {
    // default to document.body instead of documentElement to avoid output of potentially-large
    // head elements (such as JSS style blocks) in debug output
    baseElement = document.body
}
if (!container) {
    container = baseElement.appendChild(document.createElement('div'))
}
// ...

For example:

import { render } from '@testing-library/react';
import React from 'react';

function MyComponent() {
  return <main>my component</main>;
}

describe('69027456', () => {
  it('Should render correctly', () => {
    const { container } = render(<MyComponent />);
    expect(container).toMatchSnapshot();
  });
  it('Should render correctly - 2', () => {
    const { container } = render(<MyComponent />);
    expect(container.firstChild).toMatchSnapshot();
  });
});

Snapshots:

exports[`69027456 Should render correctly - 2 1`] = `
<main>
  my component
</main>
`;

exports[`69027456 Should render correctly 1`] = `
<div>
  <main>
    my component
  </main>
</div>
`;

The root element of MyComponent is the main element.

like image 127
slideshowp2 Avatar answered Sep 07 '25 21:09

slideshowp2