【问题标题】:react-testing-library - Screen vs Render queriesreact-testing-library - 屏幕与渲染查询
【发布时间】:2020-08-12 09:32:20
【问题描述】:

有两种方法可以使用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()

但是文档中没有说明哪个是最好的选择以及为什么。

谁能启发我?

【问题讨论】:

    标签: javascript reactjs react-testing-library


    【解决方案1】:

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

    使用屏幕的好处是您不再需要在添加/删除所需查询时保持渲染调用解构是最新的。您只需要输入屏幕。让您的编辑器神奇的自动完成功能来处理其余的事情。

    唯一的例外是,如果您正在设置可能应该避免这样做的容器或 baseElement(老实说,我再也想不出这些选项的合法用例了,它们目前仅出于历史原因而存在)。

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

    【讨论】:

    • 这部分是什么意思? keep the render call destructure up-to-date as you add/remove the queries you need
    • @BradyDowling render 返回一个可以解构的对象,例如const { getByText } = render(&lt;MyComponent /&gt;)。如果要使用另一个查询,则必须更新此解构对象:const { getByText, getByLabelText } = render(&lt;MyComponent /&gt;)。使用screen,所有方法都在对象本身上可用(screen.getByTextscreen.getByLabelText 等)
    • @JoeyM-H With screen, all the methods are available on the object itself 从渲染返回的组件似乎已经如此。似乎您可以跳过对渲染组件的解构并获得相同的好处,但我相信我错过了一些重要的东西。
    • @BradyDowling 你是对的,但是使用全局导入的screen 而不是每次都将来自render() 的返回分配给一个变量,特别是如果你是在一个文件中编写大量测试。这是该功能的 PR,作者github.com/testing-library/dom-testing-library/pull/412 的解释更长,显然它也有助于避免其他一些极端情况。
    • 从讨论中可以看出,渲染函数返回的对象可能是特定于框架的,但 screen 对象将与框架无关,从而使您的测试在项目之间更具弹性和一致性。
    【解决方案2】:

    screen@testing-library/dom 提供,这是 @testing-library/react 的基础。使用screen 方法时,它们将在html &lt;body&gt; 元素内进行查询,如docs 中所述:

    因为查询整个 document.body 很常见,DOM 测试库还导出了一个 screen 对象,其中每个查询都预先绑定到 document.body

    render() 仅在 @testing-library/react 中。它返回一个类似于screen 的对象,默认情况下还将查询绑定到&lt;body&gt;。默认情况下,差别不大,但您可以通过passing in options自定义其行为。

    例如,您可以在specify an element以外的&lt;body&gt;内进行查询,甚至可以提供custom query methods

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

    您不需要经常指定选项

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-15
      • 1970-01-01
      • 2021-07-05
      • 2020-04-23
      • 2021-03-03
      • 2020-05-20
      • 2020-02-27
      相关资源
      最近更新 更多