Hacktoberfest 2026:维护者为十月标记出来的 issue,仍然开放、适合新手。 浏览 Hacktoberfest issue

queries returned by render are not scoped

未关闭
#1,268 4 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

评估

难度
5/5
预计耗时
一周以上
新手友好度
35/100
Issue 类型
功能
描述清晰度
描述清楚
活跃度
停滞
技术栈
javascript, react

调研方向

首先检查 render 如何返回其查询,以及 within(container) 如何绑定查询。然后复现所提供的示例,并验证 render 的查询仅在返回的容器中进行搜索,而 screen 仍然可以搜索更广泛的文档。breaking-change 和发布的影响需要在实现之前解决。

由索引模型根据 Issue 内容生成。

描述

  • @testing-library/react version: 14.1.2
  • Testing Framework and version: Jest 29.7
  • DOM Environment: jsdom 20.0.3
Relevant code or config:
it('uses a consistent scope', () => {
  const MyComponent = () => {
    useEffect(() => {
      const separateElement = document.createElement('div');
      separateElement.textContent = 'hello';
      document.body.append(separateElement);
      return () => separateElement.remove();
    }, []);

    return (
      <div>
        <div>hello</div>
      </div>
    );
  };
  const { container, getByText } = render(<MyComponent />);

  within(container).getByText('hello'); // passes
  getByText('hello');                   // fails (finds 2 elements)
});
What happened:

The first test (within(container).getByText('hello')) passes, and the second (getByText('hello')) fails:

Found multiple elements with the text: hello

Here are the matching elements:

Ignored nodes: comments, script, style
<div>
  hello
</div>

Ignored nodes: comments, script, style
<div>
  hello
</div>
Problem description:

The container and queries returned by render should be consistent with each other: the queries should search within the returned container by default, to avoid pollution from other tests and libraries which attach elements to other parts of the DOM. For users who need to check the wider document, they can continue to use screen.

It is also worth noting that the documentation claims that the queries are "bound", which does not match the current behaviour (since they apply globally across the document).

Suggested solution:

It is possible to make a wrapper function in user-space which works around this, which should be easy to integrate into the core library:

export const renderScoped = (ui: ReactElement, options?: RenderOptions) => {
  const rendered = render(ui, options);
  return {
    ...rendered,
    ...within(rendered.container),
  };
};

This will be a potentially breaking change for users who currently rely on the queries not being scoped, so probably needs to be a "4.2" release.

主要语言
JavaScript
星标
19.7k
派生
1.2k
PR 合并指标
30 天内没有已合并 PR

环境准备

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

testing-library/react-testing-library 的其他 Issue

查看 testing-library/react-testing-library 的全部 Issue

相似的 Issue

更多 JavaScript Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。