【问题标题】:Checking text appears inside an element using react testing library使用反应测试库检查文本是否出现在元素内
【发布时间】:2020-03-17 11:08:08
【问题描述】:

我正在使用 Testing Library 为 React 应用程序编写一些测试。我想检查是否出现了一些文本,但我需要检查它是否出现在特定位置,因为我知道它已经出现在其他地方。

Testing Library documentation for queries 表示getByText 查询采用container 参数,我猜它可以让您在该容器中搜索。我尝试使用containertext 参数按照文档中指定的顺序执行此操作:

const container = getByTestId('my-test-id');
expect(getByText(container, 'some text')).toBeTruthy();

我得到一个错误:matcher.test is not a function

如果我把参数反过来:

const container = getByTestId('my-test-id');
expect(getByText('some text', container)).toBeTruthy();

我得到一个不同的错误:Found multiple elements with the text: some text

这意味着它没有在指定的容器内搜索。

我想我不明白getByText 的工作原理。我做错了什么?

【问题讨论】:

    标签: javascript reactjs react-testing-library


    【解决方案1】:

    最好使用within 处理这类事情:

    const { getByTestId } = render(<MyComponent />)
    const { getByText } = within(getByTestId('my-test-id'))
    expect(getByText('some text')).toBeInTheDocument()
    

    【讨论】:

    • 如果文本找不到,getByText 会抛出错误。那么使用expect....toBeInTheDocument有什么意义呢?
    【解决方案2】:

    另一种方法

    import {render, screen} from '@testing-library/react';
    
    ...
    
      render(<MyComponent />);
      expect(screen.getByTestId('my-test-id')).toHaveTextContent('some text');
    

    注意现在建议使用screen而不是渲染结果。

    (StackOverflow 将这些点发布到 KC Dobbs 文章中,解释原因:react-testing-library - Screen vs Render queries

    【讨论】:

    • 您可能需要添加import "@testing-library/jest-dom/extend-expect"; 才能访问toHaveTextContent 匹配器,如here 所述。
    • "...推荐使用 screen..." 但是你呢?推荐的人提供链接,而不是夸夸其谈。
    • 这是屏幕上的另一个 SO 帖子 vs 渲染指向 KC Dobbs 的解释:stackoverflow.com/questions/61482418/…
    猜你喜欢
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    • 2011-04-20
    • 1970-01-01
    • 2022-11-11
    • 2012-09-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多