【Bun中文文档-Test runner】DOM testing

229 阅读1分钟

Bun 的测试运行器与现有的组件和 DOM 测试库(包括 React Testing Library 和Happy DOM)很好地协作。

Happy DOM

如果要为前端代码和组件编写无头测试,我们建议使用Happy DOM。Happy DOM 在纯 JavaScript 中实现了一套完整的 HTML 和 DOM API,使得可以以高度逼真的方式模拟浏览器环境。

要开始使用 Happy DOM,请将@happy-dom/global-registrator包安装为开发依赖项。

$ bun add -d @happy-dom/global-registrator

我们将使用 Bun 的预加载功能来在运行测试之前注册happy-dom全局。这一步将使浏览器 API(如document)在全局范围内可用。在项目的根目录中创建一个名为happydom.ts的文件,并添加以下代码:

import { GlobalRegistrator } from "@happy-dom/global-registrator";

GlobalRegistrator.register();

要在运行bun test之前预加载此文件,请打开或创建一个bunfig.toml文件,并添加以下行。

[test]
preload = "./happydom.ts"

这将在运行bun test时执行happydom.ts。现在,您可以编写使用浏览器 API(如documentwindow)的测试。

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

test('dom test', () => {
  document.body.innerHTML = `<button>My button</button>`;
  const button = document.querySelector('button');
  expect(button?.innerText).toEqual('My button');
});

根据您的tsconfig.json设置,您可能会在上面的代码中看到一个"Cannot find name 'document'"类型错误。为了为document和其他浏览器 API“注入”类型,向任何测试文件的顶部添加以下三斜线指令

+ /// <reference lib="dom" />

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

  test('dom test', () => {
    document.body.innerHTML = `<button>My button</button>`;
    const button = document.querySelector('button');
    expect(button?.innerText).toEqual('My button');
  });

让我们使用bun test运行这个测试:

$ bun test
bun test v1.x

dom.test.ts:
✓ dom test [0.82ms]

 1 pass
 0 fail
 1 expect() calls
Ran 1 tests across 1 files. 1 total [125.00ms]