react-testing-library - 屏幕与渲染查询

react-testing-library - Screen vs Render queries

有两种使用查询的方法 react-testing-library

您可以使用 render 方法返回的查询:

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

...

const { getByText } = render(<div>Foo</div>)

expect(getByText('Foo')).toBeInTheDocument()

或者您可以使用 screen 对象:

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

...

render(<div>Foo</div>)

expect(screen.getByText('Foo')).toBeInTheDocument()

但是文档中没有说明哪一个是最好的选择以及原因。

谁能赐教一下?

screen@testing-library/dom 提供,这是 @testing-library/react 的基础。使用 screen 方法时,它们将在 html <body> 元素内查询,如 docs:

中所述

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

render() 仅在 @testing-library/react。它 returns 是一个类似于 screen 的对象,默认情况下也将查询绑定到 <body>。默认情况下,差别不大,但您可以通过 passing in options.

自定义其行为

例如,您可以 specify an element other than the <body> to query within, and can even provide custom query methods.

为了回答您关于哪个最好的问题,我会说使用 render() 更好,因为 options 使其更灵活,但引用 docs:

You won't often need to specify options

不过,我更喜欢使用 render() 提供的方法,因为如果您决定添加选项,则无需记住更改所有查询。

react-testing-library作者Kent C. Dodds本人最新推荐的方案是使用screen.

The benefit of using screen is you no longer need to keep the render call destructure up-to-date as you add/remove the queries you need. You only need to type screen. and let your editor's magic autocomplete take care of the rest.

The only exception to this is if you're setting the container or baseElement which you probably should avoid doing (I honestly can't think of a legitimate use case for those options anymore and they only exist for historical reasons at this point).

来源:https://kentcdodds.com/blog/common-mistakes-with-react-testing-library#not-using-screen

只需添加到测试文件的第一行,以允许访问虚拟 DOM 元素,

/**
 *  @jest-environment jsdom
 */

参考:

  1. Related bug
  2. Documentation
  3. Common mistakes