RTL 中的 getByText 和 screen.getByText 有什么区别

What is the difference between getByText and screen.getByText in RTL

我是 React-Testing-Library 的新手,在网上找到了一些使用 view.getByText('Greeting')screen.getByText('Greeting') 的示例,如下面的代码所示。

它们有什么区别吗?

    import React from 'react'
    import { render, screen } from '@testing-library/react'
    import '@testing-library/jest-dom/extend-expect'
    import { App } from "./App";
    
    test("render the correct context", ()=>{
      const view = render(<App />);
      view.getByText("Greeting");
      screen.getByText("Greeting");
    });

谁能详细告诉我一下?

view只是render的结果,所以在docs中我们看到:

The render method returns a promise which resolves with an object that has a few properties:

...queries#

The most important feature of render is that the queries from DOM Testing Library are automatically returned with their first argument bound to the results of rendering your component.

所以您的 App 生成了您的对象,您可以查询。 screen

screen#

All of the queries exported by DOM Testing Library accept a container as the first argument. Because querying the entire document.body is very common, DOM Testing Library also exports a screen object which has every query that is pre-bound to document.body (using the within functionality).

所以在这里查询总是查询整个body。

TLDR;他们经常同一件事。

区别

getByText会在baseElement

里面查询

screen.getByText会在document.body

里面查询

我们通常不会在 render 函数中指定自定义 containerbaseElement,这会导致它默认为 document.body

因此 getByTextscreen.getByText——或任何其他查询——通常可以互换。

import { render, screen } from '@testing-library/react'

test("render the correct context", ()=>{
  const { getByText } = render(<App />, { baseElement });
  getByText("Greeting"); // queries inside baseElement (which usually means document.body)
  screen.getByText("Greeting"); // queries inside document.body
});

你应该使用哪一个

我认为这无关紧要,无论哪种方式你都应该没问题。也就是说,库 advocates for screen 的创建者还提到您应该避免使用 containerbaseElement 渲染选项。


有用的链接