使用 TWD 测试 shadcn/ui 组件

发布: (2025年12月24日 GMT+8 05:56)
3 min read
原文: Dev.to

Source: Dev.to

Cover image for Testing shadcn/ui components with TWD

Introduction

我已经搭建了一个小型文档站点,展示 如何使用 TWD 测试 shadcn/ui 组件,它基于 Testing Library 构建。

如果你已经在使用 Testing Library,这意味着你可以保持相同的查询和断言,同时获得“开发时测试”(Testing While Developing)的好处:在构建 UI 时直接在真实应用中运行测试。

这种方法可以帮助:

  • 在真实页面中验证真实的 shadcn 组件
  • 将手动 UI 检查转化为可重复的测试
  • 让测试更贴近真实用户交互
  • 复用 Testing Library 的知识和模式

你可以在这里找到文档和示例:

目标不是取代现有的测试工具,而是让 UI 测试成为 日常开发工作流 的一部分。

Example: testing a Collapsible component

给定一个简单的 shadcn/ui Collapsible 组件:

import { Button } from "@/components/ui/button";
import {
  Collapsible,
  CollapsibleContent,
  CollapsibleTrigger,
} from "@/components/ui/collapsible";

export function CollapsibleDemo() {
  return (
    
      
        Toggle content
      
      
        
          Here is some hidden content
        
      
    
  );
}

使用 TWD 时,测试侧重于真实的用户行为,并使用熟悉的 Testing Library 风格的查询:

import { twd, screenDom, userEvent } from 'twd-js';
import { describe, it, expect } from 'twd-js/runner';

describe('Collapsible Component', () => {
  it('toggles content visibility on trigger click', async () => {
    await twd.visit('/collapsible');

    const toggleButton = await screenDom.findByRole('button', { name: 'Toggle content' });
    twd.should(toggleButton, 'be.visible');

    // Initially collapsed (content not in DOM)
    let content = screenDom.queryByText('Here is some hidden content');
    expect(content).eql(null);

    // Open
    await userEvent.click(toggleButton);
    const opened = await screenDom.findByText('Here is some hidden content');
    twd.should(opened, 'be.visible');

    // Close
    await userEvent.click(toggleButton);
    const closed = screenDom.queryByText('Here is some hidden content');
    expect(closed).eql(null);
  });
});

该测试在真实的应用中运行,验证组件的行为正如用户实际交互时的表现。

Back to Blog

相关文章

阅读更多 »