RTL 中的 `container` 和 `container.firstChild` 有什么区别

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

比如我做snapshot测试的时候,这样写有什么区别:

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

与我指定 container.firstChild

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

我无法google回答这个问题。

container is a new div element appended into baseElement 元素。默认 baseElementdocument.body。要获取渲染组件的根元素,请使用 container.firstChild.

可以从render函数的源代码中找到。

// ...
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'))
}
// ...

例如:

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();
  });
});

快照:

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

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

MyComponent 的根元素是 main 元素。