test-coverage
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseTest Coverage Fix
测试覆盖率修复
Fix test coverage for $ARGUMENTS (or the whole app if no argument is given). This skill enforces the 80% line coverage hard gate required for Dune app approval by finding AND fixing coverage gaps. Work through every step in order.
修复**$ARGUMENTS的测试覆盖率(若未提供参数则修复整个应用)。此技能通过发现并修复覆盖率缺口,确保Dune应用达到审批所需的80%行覆盖率硬性要求**。请按顺序完成每一步骤。
Step 1 — Verify test framework and coverage tooling
步骤1 — 验证测试框架与覆盖率工具
Check that the project has a working test framework with coverage configured:
bash
undefined检查项目是否已配置可用的测试框架及覆盖率工具:
bash
undefinedCheck for vitest or jest in package.json
Check for vitest or jest in package.json
grep -E "(vitest|jest)" package.json
grep -E "(vitest|jest)" package.json
Check for coverage configuration
Check for coverage configuration
cat vitest.config.ts 2>/dev/null || cat vitest.config.js 2>/dev/null || cat jest.config.ts 2>/dev/null || cat jest.config.js 2>/dev/null
Verify:
- A test framework (Vitest or Jest) is installed and configured
- The config file has a `coverage` section (e.g. `coverage: { provider: 'v8', ... }` in vitest.config.ts)
- A coverage reporter is configured (at least `text` and `lcov` or `json-summary`)
**If coverage tooling is not configured, fix it now:**
1. Install the coverage provider:
```bash
pnpm add -D @vitest/coverage-v8- Add the coverage configuration to . Read the existing config file, then add the
vitest.config.tssection insidecoverage:test
typescript
// vitest.config.ts — minimum coverage configuration to add
test: {
coverage: {
provider: 'v8',
reporter: ['text', 'text-summary', 'lcov'],
include: ['src/**/*.{ts,tsx}'],
exclude: [
'src/**/*.test.{ts,tsx}',
'src/**/*.spec.{ts,tsx}',
'src/**/vite-env.d.ts',
'src/main.tsx',
],
},
}Write the updated config file. If no vitest.config.ts exists at all, create one with the full wrapper.
defineConfigcat vitest.config.ts 2>/dev/null || cat vitest.config.js 2>/dev/null || cat jest.config.ts 2>/dev/null || cat jest.config.js 2>/dev/null
验证内容:
- 已安装并配置测试框架(Vitest或Jest)
- 配置文件包含`coverage`配置段(例如vitest.config.ts中的`coverage: { provider: 'v8', ... }`)
- 已配置覆盖率报告器(至少包含`text`以及`lcov`或`json-summary`)
**若未配置覆盖率工具,请立即修复:**
1. 安装覆盖率提供器:
```bash
pnpm add -D @vitest/coverage-v8- 向中添加覆盖率配置。读取现有配置文件,然后在
vitest.config.ts内添加test配置段:coverage
typescript
// vitest.config.ts — minimum coverage configuration to add
test: {
coverage: {
provider: 'v8',
reporter: ['text', 'text-summary', 'lcov'],
include: ['src/**/*.{ts,tsx}'],
exclude: [
'src/**/*.test.{ts,tsx}',
'src/**/*.spec.{ts,tsx}',
'src/**/vite-env.d.ts',
'src/main.tsx',
],
},
}写入更新后的配置文件。若完全不存在vitest.config.ts,则创建包含完整包装的配置文件。
defineConfigStep 2 — Validate coverage scope
步骤2 — 验证覆盖范围
The 80% threshold applies to all and files under , excluding only:
.ts.tsxsrc/- Test files (,
*.test.ts,*.test.tsx,*.spec.ts)*.spec.tsx - Type declaration files ()
vite-env.d.ts - The entry point ()
main.tsx
Apps must not exclude pages, components, hooks, or other production code from coverage measurement.
bash
undefined80%的阈值适用于下的所有和文件,仅排除以下文件:
src/.ts.tsx- 测试文件(、
*.test.ts、*.test.tsx、*.spec.ts)*.spec.tsx - 类型声明文件()
vite-env.d.ts - 入口文件()
main.tsx
应用不得将页面、组件、hooks或其他生产代码排除在覆盖率统计之外。
bash
undefinedCheck what files are excluded from coverage in the config
Check what files are excluded from coverage in the config
grep -A 20 "exclude" vitest.config.ts 2>/dev/null || grep -A 20 "exclude" vitest.config.js 2>/dev/null
grep -A 20 "exclude" vitest.config.ts 2>/dev/null || grep -A 20 "exclude" vitest.config.js 2>/dev/null
Check for coveragePathIgnorePatterns in jest config
Check for coveragePathIgnorePatterns in jest config
grep -A 10 "coveragePathIgnorePatterns|collectCoverageFrom" jest.config.ts 2>/dev/null
**If the config excludes production files, fix it now:**
Remove any exclusion that hides production code from coverage measurement. Only test files, type declarations, and the entry point should be excluded. Rewrite the `exclude` array to contain only:
```typescript
exclude: [
'src/**/*.test.{ts,tsx}',
'src/**/*.spec.{ts,tsx}',
'src/**/vite-env.d.ts',
'src/main.tsx',
],Specifically remove any exclusions for:
- or
src/pages/orsrc/components/— NOT allowedsrc/hooks/ - Specific feature files — NOT allowed unless they are generated code
- (all components) — NOT allowed, this hides the majority of the app
src/**/*.tsx
Write the corrected config file.
grep -A 10 "coveragePathIgnorePatterns|collectCoverageFrom" jest.config.ts 2>/dev/null
**若配置文件排除了生产文件,请立即修复:**
移除所有隐藏生产代码的排除规则。仅应排除测试文件、类型声明文件和入口文件。将`exclude`数组重写为仅包含以下内容:
```typescript
exclude: [
'src/**/*.test.{ts,tsx}',
'src/**/*.spec.{ts,tsx}',
'src/**/vite-env.d.ts',
'src/main.tsx',
],特别移除以下排除规则:
- 、
src/pages/或src/components/—— 不允许src/hooks/ - 特定功能文件 —— 不允许,除非是生成的代码
- (所有组件) —— 不允许,这会隐藏应用的大部分代码
src/**/*.tsx
写入修正后的配置文件。
Step 3 — Run tests and collect coverage
步骤3 — 运行测试并收集覆盖率数据
bash
undefinedbash
undefinedTry common coverage commands based on project setup
Try common coverage commands based on project setup
npx vitest run --coverage 2>/dev/null || npx jest --coverage 2>/dev/null || npm test -- --coverage 2>/dev/null
Record the coverage summary:
- **Statements:** X%
- **Branches:** X%
- **Functions:** X%
- **Lines:** X%
**Hard gate:** Overall line coverage must be **at least 80%**. Apps below this threshold are listed as **must fix**.
**If tests fail to run, fix them now:**
Common fixes:
- **Missing imports:** Read the failing test file, add the missing import statement, write the fixed file.
- **Broken mocks:** Read the test to understand what is being mocked. Fix the mock to match the current API of the mocked module.
- **Outdated snapshots:** Run `npx vitest run --update` to update snapshots, then review the diff to ensure correctness.
- **Missing dependencies:** Run `pnpm add -D <missing-package>` for any test utilities not yet installed.
- **Config errors:** Read the config file, fix syntax or option errors, write the corrected file.
Re-run tests after each fix until all tests pass. Then record the coverage summary.
---npx vitest run --coverage 2>/dev/null || npx jest --coverage 2>/dev/null || npm test -- --coverage 2>/dev/null
记录覆盖率摘要:
- **语句覆盖率:** X%
- **分支覆盖率:** X%
- **函数覆盖率:** X%
- **行覆盖率:** X%
**硬性要求:** 整体行覆盖率必须**至少达到80%**。低于此阈值的应用会被标记为**必须修复**。
**若测试运行失败,请立即修复:**
常见修复方案:
- **缺失导入:** 读取失败的测试文件,添加缺失的导入语句,写入修复后的文件。
- **Mock失效:** 读取测试内容以了解要Mock的对象。修复Mock使其匹配被Mock模块的当前API。
- **快照过时:** 运行`npx vitest run --update`更新快照,然后检查差异确保正确性。
- **缺失依赖:** 运行`pnpm add -D <缺失包>`安装任何未安装的测试工具。
- **配置错误:** 读取配置文件,修复语法或选项错误,写入修正后的文件。
每次修复后重新运行测试,直至所有测试通过。然后记录覆盖率摘要。
---Step 4 — Find and write missing test files
步骤4 — 查找并编写缺失的测试文件
For every non-trivial / file under , check whether a corresponding test file exists:
.ts.tsxsrc/bash
undefined针对下每个非平凡的/文件,检查是否存在对应的测试文件:
src/.ts.tsxbash
undefinedList all production files and check for test counterparts
List all production files and check for test counterparts
for file in $(find src -name ".ts" -o -name ".tsx" | grep -v ".test." | grep -v ".spec." | grep -v "node_modules" | grep -v "vite-env" | sort); do
base="${file%.}"
ext="${file##.}"
dir=$(dirname "$file")
filename=$(basename "$base")
Check for test file in same directory or tests directory
test_exists="false"
for pattern in "${base}.test.${ext}" "${base}.spec.${ext}" "${base}.test.ts" "${base}.spec.ts" "${dir}/tests/${filename}.test.${ext}" "${dir}/tests/${filename}.spec.${ext}"; do
if [ -f "$pattern" ]; then
test_exists="true"
break
fi
done
if [ "$test_exists" = "false" ]; then
echo "NO TEST: $file"
fi
done
Categorize each file without a test:
- **Services, hooks, utils, contexts, ViewModel hooks** — **Write the test file now** (see below)
- **Pure presentational components** with no logic — Mark as **N/A** (no test required)
- **Barrel exports** (`index.ts` that only re-exports) — Mark as **N/A**
- **Type-only files** (`.d.ts`, files with only type/interface exports) — Mark as **N/A**
**For each file missing a test, create a comprehensive test file.** Use context injection for dependency mocking where the production code supports it. If the production code uses hard-coded imports, note this as a testability concern but still write the test using `vi.mock` with a justification comment. Follow this process for each:
1. **Read the source file** to understand its exports, dependencies, and logic.
2. **Create a `.test.ts` or `.test.tsx` file** in the same directory as the source file.
3. **Write tests covering:** happy path, error path, empty state, and edge cases.
Use the right testing pattern for each file type:
**For hooks:**
- Test with `renderHook` from `@testing-library/react`
- Wrap with necessary providers (QueryClientProvider, custom context providers, etc.)
- Test initial state, loading state, success state, and error state
- Example structure:
```typescript
import { renderHook, waitFor } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
// import the hook
const createWrapper = () => {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
return ({ children }: { children: React.ReactNode }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
);
};
describe('useMyHook', () => {
it('returns data on success', async () => {
const { result } = renderHook(() => useMyHook(), { wrapper: createWrapper() });
await waitFor(() => expect(result.current.data).toBeDefined());
});
it('handles errors', async () => {
// set up error condition
const { result } = renderHook(() => useMyHook(), { wrapper: createWrapper() });
await waitFor(() => expect(result.current.error).toBeDefined());
});
});For services/utils:
- Test with direct function calls
- Mock CDF SDK responses where needed
- Test return values, side effects, and thrown errors
- Example structure:
typescript
import { describe, it, expect, vi } from 'vitest';
// import the service/util functions
describe('myService', () => {
it('returns expected result for valid input', () => {
const result = myFunction(validInput);
expect(result).toEqual(expectedOutput);
});
it('throws on invalid input', () => {
expect(() => myFunction(invalidInput)).toThrow();
});
});For components with logic:
- Test with from
render@testing-library/react - Verify loading, error, and data states
- Test user interactions that trigger state changes
- Example structure:
typescript
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
// import the component and providers
describe('MyComponent', () => {
it('shows loading state initially', () => {
render(<MyComponent />, { wrapper: createWrapper() });
expect(screen.getByText(/loading/i)).toBeInTheDocument();
});
it('renders data after loading', async () => {
render(<MyComponent />, { wrapper: createWrapper() });
await waitFor(() => {
expect(screen.getByText('expected content')).toBeInTheDocument();
});
});
});Dependency mocking guidelines:
- Use context injection (not ) where possible — provide test dependencies via the hook's context.
vi.mock - If the production code uses hard-coded imports that prevent context injection, use with a justification comment explaining why (e.g.,
vi.mock).// vi.mock required: useDataSource uses direct import, not context injection - Ensure mocks are type-safe — no casts. Define proper mock objects that satisfy the interface.
as unknown as T
After writing each test file, run to verify it passes.
npx vitest run <test-file>for file in $(find src -name ".ts" -o -name ".tsx" | grep -v ".test." | grep -v ".spec." | grep -v "node_modules" | grep -v "vite-env" | sort); do
base="${file%.}"
ext="${file##.}"
dir=$(dirname "$file")
filename=$(basename "$base")
Check for test file in same directory or tests directory
test_exists="false"
for pattern in "${base}.test.${ext}" "${base}.spec.${ext}" "${base}.test.ts" "${base}.spec.ts" "${dir}/tests/${filename}.test.${ext}" "${dir}/tests/${filename}.spec.${ext}"; do
if [ -f "$pattern" ]; then
test_exists="true"
break
fi
done
if [ "$test_exists" = "false" ]; then
echo "NO TEST: $file"
fi
done
对每个缺失测试的文件进行分类:
- **服务、hooks、工具、上下文、ViewModel hooks** —— **立即编写测试文件**(见下文)
- 无逻辑的**纯展示组件** —— 标记为**不适用**(无需测试)
- **桶导出文件**(仅重新导出内容的`index.ts`) —— 标记为**不适用**
- **仅类型文件**(`.d.ts`、仅导出类型/接口的文件) —— 标记为**不适用**
**为每个缺失测试的文件创建全面的测试文件**。若生产代码支持依赖注入,则使用上下文注入进行依赖Mock。若生产代码使用硬编码导入,需将此标记为可测试性问题,但仍需使用`vi.mock`编写测试并添加说明注释。针对每个文件遵循以下流程:
1. **读取源文件**以理解其导出内容、依赖项和逻辑。
2. **创建`.test.ts`或`.test.tsx`文件**,与源文件位于同一目录。
3. **编写测试用例**,覆盖:正常流程、错误流程、空状态和边缘场景。
针对不同文件类型使用合适的测试模式:
**针对hooks:**
- 使用`@testing-library/react`中的`renderHook`进行测试
- 包裹必要的提供者(QueryClientProvider、自定义上下文提供者等)
- 测试初始状态、加载状态、成功状态和错误状态
- 示例结构:
```typescript
import { renderHook, waitFor } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
// import the hook
const createWrapper = () => {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
return ({ children }: { children: React.ReactNode }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
);
};
describe('useMyHook', () => {
it('returns data on success', async () => {
const { result } = renderHook(() => useMyHook(), { wrapper: createWrapper() });
await waitFor(() => expect(result.current.data).toBeDefined());
});
it('handles errors', async () => {
// set up error condition
const { result } = renderHook(() => useMyHook(), { wrapper: createWrapper() });
await waitFor(() => expect(result.current.error).toBeDefined());
});
});针对服务/工具:
- 通过直接调用函数进行测试
- 必要时Mock CDF SDK响应
- 测试返回值、副作用和抛出的错误
- 示例结构:
typescript
import { describe, it, expect, vi } from 'vitest';
// import the service/util functions
describe('myService', () => {
it('returns expected result for valid input', () => {
const result = myFunction(validInput);
expect(result).toEqual(expectedOutput);
});
it('throws on invalid input', () => {
expect(() => myFunction(invalidInput)).toThrow();
});
});针对含逻辑的组件:
- 使用中的
@testing-library/react进行测试render - 验证加载、错误和数据状态
- 测试触发状态变化的用户交互
- 示例结构:
typescript
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
// import the component and providers
describe('MyComponent', () => {
it('shows loading state initially', () => {
render(<MyComponent />, { wrapper: createWrapper() });
expect(screen.getByText(/loading/i)).toBeInTheDocument();
});
it('renders data after loading', async () => {
render(<MyComponent />, { wrapper: createWrapper() });
await waitFor(() => {
expect(screen.getByText('expected content')).toBeInTheDocument();
});
});
});依赖Mock指南:
- 尽可能使用上下文注入(而非)—— 通过hook的上下文提供测试依赖项。
vi.mock - 若生产代码使用硬编码导入导致无法使用上下文注入,则使用并添加说明注释解释原因(例如
vi.mock)。// vi.mock required: useDataSource uses direct import, not context injection - 确保Mock类型安全—— 不使用类型转换。定义符合接口要求的正确Mock对象。
as unknown as T
编写完每个测试文件后,运行验证测试通过。
npx vitest run <测试文件>Step 5 — Fix low-coverage files
步骤5 — 修复低覆盖率文件
If the coverage tool produces per-file metrics, list files below 80% line coverage:
bash
undefined若覆盖率工具生成了单文件指标,列出行覆盖率低于80%的文件:
bash
undefinedParse lcov or text output for per-file coverage
Parse lcov or text output for per-file coverage
cat coverage/coverage-summary.json 2>/dev/null | node -e "
const data = JSON.parse(require('fs').readFileSync('/dev/stdin','utf8'));
Object.entries(data).forEach(([file, metrics]) => {
if (file === 'total') return;
const pct = metrics.lines?.pct ?? 0;
if (pct < 80) console.log(pct.toFixed(1) + '% — ' + file);
});
" 2>/dev/null
**For each file below 80% coverage, read the uncovered lines from the coverage report, then add test cases that exercise those specific code paths:**
1. **Read the uncovered lines** from the coverage report. Check the `coverage/` directory for detailed per-file reports (lcov or html) that show which lines are uncovered.
2. **Read the source file** to understand what those uncovered lines do.
3. **Add test cases** that exercise those specific code paths:
- **Uncovered error paths:** Add tests that trigger error conditions (network failures, invalid input, null values, permission errors). Force errors by providing bad input or mocking dependencies to throw.
- **Uncovered branches:** Add tests for each conditional branch. If an `if/else` has only the `true` branch tested, write a test that triggers the `false` branch.
- **Uncovered functions:** Add tests that call each exported function that lacks coverage. Verify return values and side effects.
- **Uncovered catch blocks:** Mock the upstream call to reject/throw, verify the catch block behavior.
4. **Run coverage again** after adding tests to verify the file now meets 80%:
```bash
npx vitest run --coverage <test-file>Repeat until each file reaches at least 80% line coverage or you have covered all feasible paths.
cat coverage/coverage-summary.json 2>/dev/null | node -e "
const data = JSON.parse(require('fs').readFileSync('/dev/stdin','utf8'));
Object.entries(data).forEach(([file, metrics]) => {
if (file === 'total') return;
const pct = metrics.lines?.pct ?? 0;
if (pct < 80) console.log(pct.toFixed(1) + '% — ' + file);
});
" 2>/dev/null
**针对每个行覆盖率低于80%的文件,从覆盖率报告中读取未覆盖的代码行,然后添加测试用例覆盖这些特定代码路径:**
1. **读取未覆盖的代码行**。查看`coverage/`目录下的详细单文件报告(lcov或html格式),了解哪些代码行未被覆盖。
2. **读取源文件**以理解这些未覆盖代码行的功能。
3. **添加测试用例**覆盖这些特定代码路径:
- **未覆盖的错误路径:** 添加触发错误条件的测试(网络失败、无效输入、空值、权限错误)。通过提供错误输入或Mock依赖项抛出错误来强制触发错误。
- **未覆盖的分支:** 为每个条件分支添加测试。若`if/else`仅测试了`true`分支,编写触发`false`分支的测试。
- **未覆盖的函数:** 添加调用每个未覆盖的导出函数的测试。验证返回值和副作用。
- **未覆盖的catch块:** Mock上游调用使其拒绝/抛出错误,验证catch块的行为。
4. **添加测试后重新运行覆盖率统计**,验证文件现在是否达到80%覆盖率:
```bash
npx vitest run --coverage <测试文件>重复此过程,直至每个文件达到至少80%行覆盖率,或已覆盖所有可行路径。
Step 6 — Fix testability patterns
步骤6 — 修复可测试性问题
Assess and fix testability issues in the codebase:
bash
undefined评估并修复代码库中的可测试性问题:
bash
undefinedCheck for dependency injection via context
Check for dependency injection via context
grep -rn --include=".ts" --include=".tsx" "useContext|createContext" src/hooks/ src/contexts/
grep -rn --include=".ts" --include=".tsx" "useContext|createContext" src/hooks/ src/contexts/
Check for vi.mock usage (red flag for testability)
Check for vi.mock usage (red flag for testability)
grep -rn --include=".ts" --include=".tsx" "vi.mock" src/
grep -rn --include=".ts" --include=".tsx" "vi.mock" src/
Check for unsafe casts in tests
Check for unsafe casts in tests
grep -rn --include=".ts" --include=".tsx" "as unknown as" src/ | grep -E ".test.|.spec."
grep -rn --include=".ts" --include=".tsx" "as unknown as" src/ | grep -E ".test.|.spec."
Check for interface-based services
Check for interface-based services
grep -rn --include=".ts" --include=".tsx" -E "implements\s+\w+" src/
**For each testability issue found, refactor the production code to support better testing patterns. Then update the corresponding test to use the improved pattern.**
| Issue | Fix |
|-------|-----|
| Hook imports dependencies directly instead of using context | Add a context type with default dependencies. Create a context with `createContext`, provide defaults that use the real implementation. In the hook, use `useContext` to get dependencies. Tests can then provide mock dependencies via the context provider without `vi.mock`. |
| Service has no interface | Extract a TypeScript interface describing the service's public API. Have the class/object implement the interface. Tests mock against the interface, not the concrete implementation. |
| Page component mixes data fetching with rendering | Extract data logic into a `use*ViewModel` hook. The page component calls the ViewModel hook and renders based on its return value. Test the ViewModel hook separately with `renderHook`, test the page component with a mocked ViewModel. |
| Tests use `vi.mock` for modules that could use context injection | After refactoring the production code to use context injection (above), update the test to provide mock dependencies via the context provider. Remove the `vi.mock` call. Add a comment explaining the pattern. |
| Tests use `as unknown as T` casts for mocks | Define a proper mock type or object that satisfies the required interface. Replace the cast with a properly typed mock. If the interface is large, create a helper function that returns a partial mock with only the methods used, typed correctly. |
For each refactored file:
1. Read the source file and its test file.
2. Refactor the production code (add context, extract interface, extract ViewModel hook).
3. Update the test to use the improved pattern.
4. Run `npx vitest run <test-file>` to verify the test still passes.
---grep -rn --include=".ts" --include=".tsx" -E "implements\s+\w+" src/
**针对每个发现的可测试性问题,重构生产代码以支持更好的测试模式。然后更新对应的测试以使用改进后的模式。**
| 问题 | 修复方案 |
|-------|-----|
| Hook直接导入依赖项而非使用上下文 | 添加带默认依赖的上下文类型。使用`createContext`创建上下文,提供使用真实实现的默认值。在hook中使用`useContext`获取依赖项。测试时可通过上下文提供者提供Mock依赖项,无需使用`vi.mock`。 |
| 服务无接口 | 提取描述服务公共API的TypeScript接口。让类/对象实现该接口。测试针对接口进行Mock,而非具体实现。 |
| 页面组件混合数据获取与渲染逻辑 | 将数据逻辑提取到`use*ViewModel` hook中。页面组件调用ViewModel hook并根据其返回值进行渲染。单独使用`renderHook`测试ViewModel hook,使用Mock的ViewModel测试页面组件。 |
| 测试对可使用上下文注入的模块使用`vi.mock` | 在重构生产代码以使用上下文注入(如上所述)后,更新测试以通过上下文提供者提供Mock依赖项。移除`vi.mock`调用。添加注释说明该模式。 |
| 测试对Mock使用`as unknown as T`类型转换 | 定义符合所需接口的正确Mock类型或对象。用类型正确的Mock替换类型转换。若接口较大,创建辅助函数返回仅包含所用方法的部分Mock,并确保类型正确。 |
针对每个重构后的文件:
1. 读取源文件及其测试文件。
2. 重构生产代码(添加上下文、提取接口、提取ViewModel hook)。
3. 更新测试以使用改进后的模式。
4. 运行`npx vitest run <测试文件>`验证测试仍能通过。
---Step 7 — Report remaining gaps
步骤7 — 报告剩余缺口
Re-run the full test suite with coverage to get final numbers:
bash
npx vitest run --coverage 2>/dev/null || npx jest --coverage 2>/dev/nullProduce a summary of what was done and what remains:
markdown
undefined重新运行完整测试套件并收集覆盖率数据以获取最终结果:
bash
npx vitest run --coverage 2>/dev/null || npx jest --coverage 2>/dev/null生成已完成工作和剩余问题的摘要:
markdown
undefinedTest Coverage Summary (After Fixes)
测试覆盖率摘要(修复后)
| Metric | Before | After | Gate |
|---|---|---|---|
| Lines | X% | Y% | ≥80% required |
| Branches | X% | Y% | — |
| Functions | X% | Y% | — |
| Statements | X% | Y% | — |
| 指标 | 修复前 | 修复后 | 要求 |
|---|---|---|---|
| 行覆盖率 | X% | Y% | ≥80% 必需 |
| 分支覆盖率 | X% | Y% | — |
| 函数覆盖率 | X% | Y% | — |
| 语句覆盖率 | X% | Y% | — |
Coverage verdict: PASS / FAIL
覆盖率结论:通过 / 未通过
What was fixed
已修复内容
- Coverage tooling configured/corrected
- Exclusions cleaned up (removed N production file exclusions)
- N failing tests fixed
- N new test files written (list them)
- N existing test files expanded for coverage
- N files refactored for testability
- 配置/修正了覆盖率工具
- 清理了排除规则(移除了N个生产文件排除项)
- 修复了N个失败的测试
- 编写了N个新测试文件(列出文件名)
- 扩展了N个现有测试文件以提升覆盖率
- 重构了N个文件以提升可测试性
Remaining gaps (needs human review)
剩余缺口(需人工审核)
Only list issues that could not be auto-fixed:
- Complex business logic where correct test assertions require domain knowledge
- Integration tests that need real API credentials or environment setup
- Files where coverage cannot reach 80% without major architectural changes (explain why)
---仅列出无法自动修复的问题:
- 复杂业务逻辑,正确的测试断言需要领域知识
- 需要真实API凭证或环境设置的集成测试
- 无需重大架构变更无法达到80%覆盖率的文件(说明原因)
---Done
完成
Summarize:
- Overall coverage before and after fixes, vs the 80% gate (PASS or FAIL)
- Number of test files written and tests added
- Number of files refactored for testability
- Any remaining must fix items that need human review
总结:
- 修复前后的整体覆盖率,以及与80%要求的对比(通过或未通过)
- 编写的测试文件数量和添加的测试用例数量
- 为提升可测试性而重构的文件数量
- 任何剩余的必须修复项,需人工审核