twd-setup

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

TWD Project Setup Guide

TWD项目设置指南

You are helping set up TWD (Test While Developing), an in-browser testing library for SPAs. Follow these steps carefully.
Supported frameworks: React, Vue, Angular, Solid.js, Astro (with React), React Router (Framework Mode) Not compatible with: Next.js App Router, SSR-first architectures
你正在帮助设置TWD (Test While Developing),这是一个面向单页应用(SPA)的浏览器内测试库。请仔细遵循以下步骤。
支持的框架: React、Vue、Angular、Solid.js、Astro(搭配React)、React Router(框架模式) 不兼容的框架: Next.js App Router、优先SSR的架构

Step 1: Install TWD

步骤1:安装TWD

bash
npm install twd-js
bash
npm install twd-js

Step 2: Initialize Mock Service Worker

步骤2:初始化Mock Service Worker

Required for API mocking. Run this in the project root:
bash
npx twd-js init public
This copies
mock-sw.js
to the
public/
directory. If the public directory has a different name (e.g.,
static/
), use that path instead.
这是API模拟功能的必需步骤。在项目根目录运行以下命令:
bash
npx twd-js init public
该命令会将
mock-sw.js
复制到
public/
目录。如果你的静态资源目录名称不同(例如
static/
),请使用对应的路径。

Step 3: Configure Entry Point

步骤3:配置入口文件

TWD should only load in development mode. Choose the setup based on the framework:
TWD仅应在开发模式下加载。请根据你的框架选择对应的设置方式:

Bundled Setup (Recommended — all frameworks)

捆绑式设置(推荐——适用于所有框架)

typescript
// src/main.ts (or main.tsx)
if (import.meta.env.DEV) {
  const { initTWD } = await import('twd-js/bundled');
  const tests = import.meta.glob("./**/*.twd.test.ts");

  initTWD(tests, {
    open: true,
    position: 'left',
    serviceWorker: true,
    serviceWorkerUrl: '/mock-sw.js',
  });
}
initTWD options:
  • open
    (boolean) — sidebar open by default. Default:
    true
  • position
    (
    "left"
    |
    "right"
    ) — sidebar position. Default:
    "left"
  • serviceWorker
    (boolean) — enable API mocking. Default:
    true
  • serviceWorkerUrl
    (string) — service worker path. Default:
    '/mock-sw.js'
  • theme
    (object) — custom theme. See TWD theming docs.
typescript
// src/main.ts (或 main.tsx)
if (import.meta.env.DEV) {
  const { initTWD } = await import('twd-js/bundled');
  const tests = import.meta.glob("./**/*.twd.test.ts");

  initTWD(tests, {
    open: true,
    position: 'left',
    serviceWorker: true,
    serviceWorkerUrl: '/mock-sw.js',
  });
}
initTWD配置项:
  • open
    (布尔值)——默认是否打开侧边栏。默认值:
    true
  • position
    "left"
    |
    "right"
    )——侧边栏位置。默认值:
    "left"
  • serviceWorker
    (布尔值)——是否启用API模拟。默认值:
    true
  • serviceWorkerUrl
    (字符串)——Service Worker的路径。默认值:
    '/mock-sw.js'
  • theme
    (对象)——自定义主题。请查看TWD主题文档。

Standard Setup (React only — more control)

标准设置(仅适用于React——提供更多控制权)

tsx
// src/main.tsx
import { createRoot } from 'react-dom/client';

if (import.meta.env.DEV) {
  const testModules = import.meta.glob("./**/*.twd.test.ts");
  const { initTests, twd, TWDSidebar } = await import('twd-js');
  initTests(testModules, <TWDSidebar open={true} position="left" />, createRoot);
  twd.initRequestMocking().catch(console.error);
}
tsx
// src/main.tsx
import { createRoot } from 'react-dom/client';

if (import.meta.env.DEV) {
  const testModules = import.meta.glob("./**/*.twd.test.ts");
  const { initTests, twd, TWDSidebar } = await import('twd-js');
  initTests(testModules, <TWDSidebar open={true} position="left" />, createRoot);
  twd.initRequestMocking().catch(console.error);
}

Framework-Specific Notes

框架特定说明

Vue:
typescript
// src/main.ts
import { createApp } from 'vue';
import App from './App.vue';

if (import.meta.env.DEV) {
  const { initTWD } = await import('twd-js/bundled');
  const tests = import.meta.glob("./**/*.twd.test.ts");
  initTWD(tests, { open: true, position: 'left' });
}

createApp(App).mount('#app');
Angular:
typescript
// src/main.ts
import { isDevMode } from '@angular/core';

if (isDevMode()) {
  const { initTWD } = await import('twd-js/bundled');
  // Angular may not support import.meta.glob — define tests manually:
  const tests = {
    './twd-tests/feature.twd.test.ts': () => import('./twd-tests/feature.twd.test'),
  };
  initTWD(tests, { open: true, position: 'left' });
}
Solid.js:
tsx
// src/main.tsx
if (import.meta.env.DEV) {
  const { initTWD } = await import('twd-js/bundled');
  const tests = import.meta.glob("./**/*.twd.test.ts");
  initTWD(tests, { open: true, position: 'left' });
}
Vue:
typescript
// src/main.ts
import { createApp } from 'vue';
import App from './App.vue';

if (import.meta.env.DEV) {
  const { initTWD } = await import('twd-js/bundled');
  const tests = import.meta.glob("./**/*.twd.test.ts");
  initTWD(tests, { open: true, position: 'left' });
}

createApp(App).mount('#app');
Angular:
typescript
// src/main.ts
import { isDevMode } from '@angular/core';

if (isDevMode()) {
  const { initTWD } = await import('twd-js/bundled');
  // Angular可能不支持import.meta.glob——请手动定义测试文件:
  const tests = {
    './twd-tests/feature.twd.test.ts': () => import('./twd-tests/feature.twd.test'),
  };
  initTWD(tests, { open: true, position: 'left' });
}
Solid.js:
tsx
// src/main.tsx
if (import.meta.env.DEV) {
  const { initTWD } = await import('twd-js/bundled');
  const tests = import.meta.glob("./**/*.twd.test.ts");
  initTWD(tests, { open: true, position: 'left' });
}

Step 4: Add Vite HMR Plugin (Recommended)

步骤4:添加Vite HMR插件(推荐)

Prevents test entries from duplicating during hot module replacement:
typescript
// vite.config.ts
import { twdHmr } from 'twd-js/vite-plugin';

export default defineConfig({
  plugins: [
    // ... other plugins
    twdHmr(),
  ],
});
防止热模块替换(HMR)过程中测试条目重复:
typescript
// vite.config.ts
import { twdHmr } from 'twd-js/vite-plugin';

export default defineConfig({
  plugins: [
    // ... 其他插件
    twdHmr(),
  ],
});

Step 5: Write a First Test

步骤5:编写第一个测试

Create a test file to verify the setup:
typescript
// src/App.twd.test.ts
import { twd, screenDom } from "twd-js";
import { describe, it } from "twd-js/runner";

describe("App", () => {
  it("should render the main heading", async () => {
    await twd.visit("/");
    const heading = screenDom.getByRole("heading", { level: 1 });
    twd.should(heading, "be.visible");
  });
});
创建测试文件以验证设置是否成功:
typescript
// src/App.twd.test.ts
import { twd, screenDom } from "twd-js";
import { describe, it } from "twd-js/runner";

describe("App", () => {
  it("should render the main heading", async () => {
    await twd.visit("/");
    const heading = screenDom.getByRole("heading", { level: 1 });
    twd.should(heading, "be.visible");
  });
});

Step 6: Run the App

步骤6:运行应用

bash
npm run dev
The TWD sidebar should appear in the browser. Click it to view and run tests.
bash
npm run dev
浏览器中应该会出现TWD侧边栏。点击它即可查看并运行测试。

Optional: AI Remote Testing (twd-relay)

可选:AI远程测试(twd-relay)

For AI agents that need to run tests from the CLI:
bash
npm install --save-dev twd-relay
Vite plugin setup (recommended):
typescript
// vite.config.ts
import { twdRemote } from 'twd-relay/vite';

export default defineConfig({
  plugins: [
    // ... other plugins
    twdRemote(),
  ],
});
Connect browser client:
typescript
// Add inside your import.meta.env.DEV block, after initTWD:
import { createBrowserClient } from 'twd-relay/browser';
const client = createBrowserClient();
client.connect();
Run tests from CLI:
bash
npx twd-relay run
适用于需要从CLI运行测试的AI Agent:
bash
npm install --save-dev twd-relay
Vite插件设置(推荐):
typescript
// vite.config.ts
import { twdRemote } from 'twd-relay/vite';

export default defineConfig({
  plugins: [
    // ... 其他插件
    twdRemote(),
  ],
});
连接浏览器客户端:
typescript
// 在import.meta.env.DEV代码块内添加,位于initTWD之后:
import { createBrowserClient } from 'twd-relay/browser';
const client = createBrowserClient();
client.connect();
从CLI运行测试:
bash
npx twd-relay run

Troubleshooting

故障排查

Tests Not Loading

测试未加载

  • Verify
    import.meta.env.DEV
    is true (dev mode)
  • Check file naming: must be
    *.twd.test.ts
    or
    *.twd.test.tsx
  • Ensure the
    initTWD
    /
    initTests
    call is in the main entry file
  • Check the glob pattern matches your test file locations
  • 验证
    import.meta.env.DEV
    是否为true(即处于开发模式)
  • 检查文件命名:必须为
    *.twd.test.ts
    *.twd.test.tsx
    格式
  • 确保
    initTWD
    /
    initTests
    调用位于主入口文件中
  • 检查glob模式是否匹配你的测试文件位置

Mock Service Worker Issues

Mock Service Worker问题

  • Run
    npx twd-js init public
    to install the service worker
  • With standard setup: ensure
    twd.initRequestMocking()
    is called
  • Check browser console for service worker registration errors
  • 运行
    npx twd-js init public
    安装Service Worker
  • 若使用标准设置:确保调用了
    twd.initRequestMocking()
  • 检查浏览器控制台中的Service Worker注册错误

Test Duplication on HMR

HMR时测试重复

  • Add
    twdHmr()
    plugin to Vite config
  • 在Vite配置中添加
    twdHmr()
    插件

Sidebar Not Appearing

侧边栏未显示

  • Confirm you're in development mode
  • Check browser console for initialization errors
  • Ensure the entry point code runs before the app renders
  • 确认当前处于开发模式
  • 检查浏览器控制台中的初始化错误
  • 确保入口文件中的代码在应用渲染前执行