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

4

当我进行快照测试时,例如,如果我这样编写有什么区别:

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

我无法在谷歌上找到任何答案。
1个回答

4

container 是一个新的 div 元素,被添加到 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 元素。

这个在哪里有文档记录? - CodeDreamer68

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接