`screen.getByText()` 与 create-react-app 中的 `getByText()`

`screen.getByText()` vs `getByText()` in create-react-app

我正在使用 create-react-app 构建的 React 应用程序中构建测试,我试图了解 screen.getByText()getByText() 之间的区别。例如,文档显示了这种示例:

import React from 'react';
import { render, screen } from '@testing-library/react';
import App from './App';

it('renders a title of "Dashboard"', () => {
  render(<App />);
  expect(screen.getByText('Dashboard')).toBeInTheDocument();
});

但我发现我可以做到这一点:

it('renders a title of "Dashboard"', () => {
  const { getByText } = render(<App />);
  expect(getByText('Dashboard')).toBeInTheDocument();
});

我还没有发现使用 screen.getByText() 与仅使用 getByText() 之间的区别,就像我上面显示的那样。

有什么区别,在各种情况下使用一种比另一种有什么优势?

这是一个方便的事情。使用 screen 你会发现你不再需要 constantly/explicitly 解构 render 方法的 return 值来访问选择器函数(基本上就是这样) .

引入该功能的 PR 对其背后的基本原理有明确的解释:

https://github.com/testing-library/dom-testing-library/pull/412

唯一的警告是在您提供显式 container argument to the render method 的情况下 - 因为基于 screen 的选择器将匹配 document.body 上的所有元素(就像您解构render 结果,选择器函数的范围将限定为您提供的容器内的元素。

如果您刚开始使用该库,我还建议您看一下 Kent Dodds 的这篇文章(介绍该功能的人是同一人,也是该领域的重要参考),其中有一堆 goodies/best 使用测试库的实践以及每项建议背后的基本原理:

https://kentcdodds.com/blog/common-mistakes-with-react-testing-library