测试设置文件中的“ after Each( cleanup) ” 模块在 Bun 测试中导出“ 屏幕” 模块

作者: hmidmrii创建于 2024年7月30日更新于 2026年6月10日
  • @testing-library/react 版本: 15.0.7
  • 测试框架和版本: Bun test v1.1.21
  • DOM 环境: @happy-dom/[email protected]

相关代码或配置:

test.setup.ts

typescript
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

typescript
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
  });
});

你做了什么:

我只是试图使用 react 测试库导出的 screen 来测试一个组件,使用 Bun test。

内容来源: testing-library/react-testing-library