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

Having `afterEach(cleanup)` in the test setup file breaks exported `screen` module on Bun test

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

还没有人认领这个 Issue。

评估

难度
3/5
预计耗时
1-2 天
新手友好度
50/100
Issue 类型
缺陷
描述清晰度
基本清楚
活跃度
冷清
技术栈
react, typescript

调研方向

首先按照所示,使用 test.setup.ts 和 Component.spec.tsx 运行 bun test --preload test.setup.ts。跟踪 afterEach(cleanup) 如何与导出的 screen 以及 render 使用的文档交互。完成标准是:复现能够使用导出的 screen,同时保留 setup 级别的 cleanup,并包含一个覆盖 Bun 的回归测试。

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

描述

  • @testing-library/react version: 15.0.7
  • Testing Framework and version: Bun test v1.1.21
  • DOM Environment: @happy-dom/[email protected]
Relevant code or config:

test.setup.ts

import { GlobalRegistrator } from '@happy-dom/global-registrator';
import { cleanup } from '@testing-library/react';

import { expect, afterEach } from 'bun:test';

import * as matchers from '@testing-library/jest-dom/matchers';

GlobalRegistrator.register();

declare module 'bun:test' {
  interface Matchers<T> extends matchers.TestingLibraryMatchers<any, void> {}
  interface AsymmetricMatchers extends matchers.TestingLibraryMatchers<any, void> {}
}

expect.extend(matchers);

afterEach(cleanup);

Component.spec.tsx

import { act, render, screen } from '@testing-library/react';
import { TextAreaInput } from './TextAreaInput.component';
import { describe, it } from 'bun:test';

describe('TextAreaInput', () => {
  it('Should show in the DOM', async () => {
    const { getByRole } = await act(() => render(<TextAreaInput />));

    // Works fine!
    getByRole('textbox')

    // throws an error
    screen.getByRole('textbox');
    // TypeError: For queries bound to document.body a global document has to be available... Learn more: https://testing-library.com/s/screen-global-error
  });
});
What you did:

I'm just trying to test a component using the screen exported by react testing library using Bun test.

What happened:

everything was smooth, until I tried to use the screen exported from the react testing library it threw an error about "global document has to be available",
upon inspecting, removing afterEach(cleanup) from the test setup file or writing afterEach(cleanup) in each test file will make it works,

Reproduction:

just run bun test --preload test.setup.ts

Problem description:

using the screen exported while having the cleanup code in the test setup will break the test

Suggested solution:

just use the returned screen from the render function.

主要语言
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 摘要。