phase 5 part 2: vite 8, webpack 5, fe-testing-perf topics with verified examples
This commit is contained in:
1 parent
7b5cae7d24
commit
9eeb10aede
38 files changed
+1823
-37
No files matched your search
@@ -0,0 +1,13 @@
|
||||
// 不自动运行:Playwright 端到端测试示意(需要 npx playwright install 并启动被测站点;本仓库未在浏览器中实际运行)
|
||||
// 以官方文档为准:https://playwright.dev/docs/intro
|
||||
import { expect, test } from "@playwright/test";
|
||||
|
||||
test("用户搜索订单并看到结果", async ({ page }) => {
|
||||
// 拦截接口返回固定数据:端到端测试只验证前端流程,不依赖后端数据
|
||||
await page.route("**/api/orders/search**", (route) =>
|
||||
route.fulfill({ json: ["A001", "A002"] }),
|
||||
);
|
||||
await page.goto("http://localhost:5173/orders");
|
||||
await page.getByLabel("搜索订单").fill("A00");
|
||||
await expect(page.getByRole("list", { name: "搜索结果" }).getByRole("listitem")).toHaveCount(2);
|
||||
});
|
||||
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"name": "search-box-demo",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"test": "vitest run",
|
||||
"e2e": "playwright test"
|
||||
},
|
||||
"dependencies": {
|
||||
"react": "^19.2.0",
|
||||
"react-dom": "^19.2.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@playwright/test": "^1.64.0",
|
||||
"@testing-library/react": "^16.3.0",
|
||||
"@types/react": "^19.2.0",
|
||||
"@types/react-dom": "^19.2.0",
|
||||
"jsdom": "^30.0.0",
|
||||
"typescript": "^5.9.0",
|
||||
"vitest": "^5.0.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
// 不自动运行(需要 npm install 后执行 npx vitest run)
|
||||
import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { SearchBox, type SearchFn } from "./SearchBox.tsx";
|
||||
|
||||
beforeEach(() => vi.useFakeTimers());
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
function typeInto(text: string) {
|
||||
fireEvent.change(screen.getByLabelText("搜索订单"), { target: { value: text } });
|
||||
}
|
||||
|
||||
describe("SearchBox", () => {
|
||||
it("防抖:连续输入只发一次请求", async () => {
|
||||
const search = vi.fn<SearchFn>().mockResolvedValue(["A001"]);
|
||||
render(<SearchBox search={search} />);
|
||||
typeInto("A");
|
||||
typeInto("A0");
|
||||
typeInto("A00");
|
||||
await act(() => vi.advanceTimersByTimeAsync(300));
|
||||
expect(search).toHaveBeenCalledTimes(1);
|
||||
expect(search.mock.calls[0]?.[0]).toBe("A00");
|
||||
expect(screen.getByRole("list", { name: "搜索结果" }).textContent).toContain("A001");
|
||||
});
|
||||
|
||||
it("竞态:慢的旧请求晚返回,不会覆盖新结果", async () => {
|
||||
const search: SearchFn = (q, signal) =>
|
||||
new Promise((resolve) => {
|
||||
const ms = q === "old" ? 1000 : 100; // 旧关键词的请求更慢
|
||||
const t = setTimeout(() => resolve([`结果-${q}`]), ms);
|
||||
signal.addEventListener("abort", () => clearTimeout(t));
|
||||
});
|
||||
render(<SearchBox search={search} />);
|
||||
typeInto("old");
|
||||
await act(() => vi.advanceTimersByTimeAsync(300)); // 发出 old 请求
|
||||
typeInto("new");
|
||||
await act(() => vi.advanceTimersByTimeAsync(2000)); // 两个请求都有时间完成
|
||||
const list = screen.getByRole("list", { name: "搜索结果" });
|
||||
expect(list.textContent).toBe("结果-new");
|
||||
});
|
||||
|
||||
it("失败时显示错误提示", async () => {
|
||||
const search = vi.fn<SearchFn>().mockRejectedValue(new Error("服务繁忙"));
|
||||
render(<SearchBox search={search} />);
|
||||
typeInto("x");
|
||||
await act(() => vi.advanceTimersByTimeAsync(300));
|
||||
expect(screen.getByRole("alert").textContent).toBe("服务繁忙");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,51 @@
|
||||
// 不自动运行:React 组件,由 vitest + Testing Library 测试(npx vitest run)
|
||||
// 要点:防抖减少请求;新请求开始时中止旧请求,避免“旧结果覆盖新结果”的竞态;可访问的标签,便于测试和读屏
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
export type SearchFn = (q: string, signal: AbortSignal) => Promise<string[]>;
|
||||
|
||||
export function SearchBox({ search, delayMs = 300 }: { search: SearchFn; delayMs?: number }) {
|
||||
const [q, setQ] = useState("");
|
||||
const [items, setItems] = useState<string[]>([]);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const keyword = q.trim();
|
||||
if (!keyword) {
|
||||
setItems([]);
|
||||
return;
|
||||
}
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => {
|
||||
search(keyword, controller.signal)
|
||||
.then((r) => {
|
||||
if (!controller.signal.aborted) {
|
||||
setItems(r);
|
||||
setError(null);
|
||||
}
|
||||
})
|
||||
.catch((e: unknown) => {
|
||||
if (!controller.signal.aborted) setError(e instanceof Error ? e.message : "搜索失败");
|
||||
});
|
||||
}, delayMs);
|
||||
return () => { // 输入变化或卸载:清除定时器并中止进行中的请求
|
||||
clearTimeout(timer);
|
||||
controller.abort();
|
||||
};
|
||||
}, [q, search, delayMs]);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<label>
|
||||
搜索订单
|
||||
<input value={q} onChange={(e) => setQ(e.target.value)} />
|
||||
</label>
|
||||
{error && <p role="alert">{error}</p>}
|
||||
<ul aria-label="搜索结果">
|
||||
{items.map((it) => (
|
||||
<li key={it}>{it}</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
// 把耗时的循环切成小块,每块之间让出主线程,避免长任务(> 50ms)拖慢交互(INP)
|
||||
// 只用标准库;`node src/chunked.ts` 可以直接运行自检
|
||||
|
||||
export type Yield = () => Promise<void>;
|
||||
|
||||
// 浏览器中优先使用 scheduler.yield()(较新的 API,以 MDN 为准),否则退回 setTimeout(0)
|
||||
export const defaultYield: Yield = () => {
|
||||
const s = (globalThis as { scheduler?: { yield?: () => Promise<void> } }).scheduler;
|
||||
if (s?.yield) return s.yield();
|
||||
return new Promise((resolve) => setTimeout(resolve, 0));
|
||||
};
|
||||
|
||||
export async function processInChunks<T, R>(
|
||||
items: readonly T[],
|
||||
fn: (item: T) => R,
|
||||
options: { budgetMs?: number; yieldFn?: Yield; now?: () => number } = {},
|
||||
): Promise<{ results: R[]; yields: number }> {
|
||||
const { budgetMs = 8, yieldFn = defaultYield, now = () => performance.now() } = options;
|
||||
const results: R[] = [];
|
||||
let yields = 0;
|
||||
let start = now();
|
||||
for (const item of items) {
|
||||
results.push(fn(item));
|
||||
if (now() - start >= budgetMs) { // 本块用完预算:让出主线程,让浏览器处理点击和渲染
|
||||
await yieldFn();
|
||||
yields++;
|
||||
start = now();
|
||||
}
|
||||
}
|
||||
return { results, yields };
|
||||
}
|
||||
|
||||
// 自检
|
||||
if (import.meta.url === `file://${process.argv[1]}`) {
|
||||
let fake = 0;
|
||||
const { results, yields } = await processInChunks(
|
||||
Array.from({ length: 100 }, (_, i) => i),
|
||||
(x) => x * 2,
|
||||
{ budgetMs: 10, now: () => (fake += 1), yieldFn: async () => {} }, // 假时钟:每次调用 +1ms
|
||||
);
|
||||
if (results.length !== 100 || results[99] !== 198) throw new Error("结果错误");
|
||||
if (yields < 5) throw new Error(`应该多次让出主线程,实际 ${yields}`);
|
||||
console.log(`处理 ${results.length} 条,让出主线程 ${yields} 次`);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"jsx": "react-jsx",
|
||||
"strict": true,
|
||||
"noEmit": true,
|
||||
"skipLibCheck": true,
|
||||
"allowImportingTsExtensions": true,
|
||||
"lib": ["ES2022", "DOM", "DOM.Iterable"],
|
||||
"types": ["node"]
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
// 不自动运行:vitest 的配置文件
|
||||
import { defineConfig } from "vitest/config";
|
||||
|
||||
export default defineConfig({
|
||||
test: {
|
||||
environment: "jsdom", // 组件测试需要 DOM
|
||||
include: ["src/**/*.test.ts", "src/**/*.test.tsx"],
|
||||
},
|
||||
});
|
||||
Reference in new issue
Block a user