twd-setup
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseTWD 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-jsbash
npm install twd-jsStep 2: Initialize Mock Service Worker
步骤2:初始化Mock Service Worker
Required for API mocking. Run this in the project root:
bash
npx twd-js init publicThis copies to the directory. If the public directory has a different name (e.g., ), use that path instead.
mock-sw.jspublic/static/这是API模拟功能的必需步骤。在项目根目录运行以下命令:
bash
npx twd-js init public该命令会将复制到目录。如果你的静态资源目录名称不同(例如),请使用对应的路径。
mock-sw.jspublic/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:
- (boolean) — sidebar open by default. Default:
opentrue - (
position|"left") — sidebar position. Default:"right""left" - (boolean) — enable API mocking. Default:
serviceWorkertrue - (string) — service worker path. Default:
serviceWorkerUrl'/mock-sw.js' - (object) — custom theme. See TWD theming docs.
theme
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配置项:
- (布尔值)——默认是否打开侧边栏。默认值:
opentrue - (
position|"left")——侧边栏位置。默认值:"right""left" - (布尔值)——是否启用API模拟。默认值:
serviceWorkertrue - (字符串)——Service Worker的路径。默认值:
serviceWorkerUrl'/mock-sw.js' - (对象)——自定义主题。请查看TWD主题文档。
theme
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 devThe 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-relayVite 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-relayVite插件设置(推荐):
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 runTroubleshooting
故障排查
Tests Not Loading
测试未加载
- Verify is true (dev mode)
import.meta.env.DEV - Check file naming: must be or
*.twd.test.ts*.twd.test.tsx - Ensure the /
initTWDcall is in the main entry fileinitTests - Check the glob pattern matches your test file locations
- 验证是否为true(即处于开发模式)
import.meta.env.DEV - 检查文件命名:必须为或
*.twd.test.ts格式*.twd.test.tsx - 确保/
initTWD调用位于主入口文件中initTests - 检查glob模式是否匹配你的测试文件位置
Mock Service Worker Issues
Mock Service Worker问题
- Run to install the service worker
npx twd-js init public - With standard setup: ensure is called
twd.initRequestMocking() - Check browser console for service worker registration errors
- 运行安装Service Worker
npx twd-js init public - 若使用标准设置:确保调用了
twd.initRequestMocking() - 检查浏览器控制台中的Service Worker注册错误
Test Duplication on HMR
HMR时测试重复
- Add plugin to Vite config
twdHmr()
- 在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
- 确认当前处于开发模式
- 检查浏览器控制台中的初始化错误
- 确保入口文件中的代码在应用渲染前执行