Skip to content

调试测试

Diagnose failing, flaky, and hanging 测试使用 logs, inspectors, and isolation.

你将学到

  • 读取失败输出到 locate broken assertion 快
  • Using --inspect, console, and screen 调试到 see 内部测试
  • Tracking 下 flaky 测试使用 repetition and seed control
  • Isolating failing 测试从 REST 的 suite

概念讲解

Read the Failure First

The test runner's failure output tells you the file, the describe path, the failing assertion, and the expected vs actual values. Read this before reaching for a debugger. A good failure message — which is why naming matters — often pinpoints the bug in seconds. If the diff is unclear, add a more specific assertion or log the actual value to see its real shape.

See Inside the Test

When the failure is opaque, inspect the runtime. console.log inside a test prints to the terminal; screen.调试() (Testing Library) dumps the rendered DOM as HTML. For deep debugging, run Node with --inspect-brk and attach Chrome DevTools, or use VS Code's JavaScript debug terminal to set breakpoints inside test files. Vitest supports vitest --inspect-brk for the same workflow.

Flaky Tests

A flaky test passes sometimes and fails others — the worst kind of bug because it erodes trust in the whole suite. Find the source of non-determinism: shared state, time, random, network, test order. Run the single test in a loop (vitest 测试 -t "name" --retry 50) to reproduce the flake. Fix it by isolating state, faking time, seeding random, or removing the network call. Never disable a flaky test without filing a ticket — it will rot.

Isolate and Bisect

When a test passes alone but fails in the suite, state is leaking between tests. Run the test with the ones before it to bisect the culprit. Add beforeEach resets, restore mocks, and clear shared singletons. If a test hangs, it is usually an unawaited promise or a missing vi.runAllTimers; add a timeout (它("...", () => {}, 1000)) to fail fast instead of waiting for the CI timeout.

In Practice

Develop a debugging routine: first read the failure message and the diff; if unclear, add a console.log of the actual value to see its real shape; if still stuck, isolate the test by running it alone and then with neighbors to find leaking state. For flaky tests, run the single test in a loop (vitest -t "name" --retry 50) to reproduce the failure, then trace the non-determinism to its source — usually a shared database row, an unmocked timer, or a network call. Fix the root cause rather than adding a retry. For hangs, set an explicit test timeout so the failure is fast and obvious. Keep a log of flaky tests you have fixed so patterns emerge — if the same cause recurs, it points to a structural issue in the test setup worth addressing once and for all.

示例代码

              import { describe, it, expect, vi } from "vitest";

describe("debugging helpers", () => {
  it("logs the actual value to inspect its shape", () => {
    const result = buildReport();
    console.log("actual:", JSON.stringify(result, null, 2));
    expect(result.total).toBe(100);
  });

  it("retries a flaky test to reproduce the failure", () => {
    // Run with: vitest -t "retries a flaky" --retry 20
    const n = Math.random();
    expect(n).toBeLessThan(0.5); // fails ~50% of the time
  });

  it("fails fast with a timeout instead of hanging", () => {
    return new Promise(() => {}); // never resolves
  }, 1000); // fails after 1s instead of hanging forever
});
            

console.log shows 真实 shape 的数据, --retry reproduces flakiness, and explicit timeout turns hang 到快, 清晰失败.

动手试一试

  • Code Diff

    Compare expected 对比实际从 failing assertion.

  • JSON Formatter

    Pretty-print logged 对象你 inspect 虽然调试.

常见错误

错误写法

Skipping or commenting out flaky 测试

正确做法

Reproduce and fix flakiness, or quarantine 使用 tracked ticket. skipped 测试是 隐藏 rot 那个 lets 真实 bugs 通过.

错误写法

调试整个 suite at 一次

正确做法

Isolate failing 测试首先 (运行它 alone), 然后 bisect 通过添加 neighbors 直到它 breaks. leak 是 in difference.

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误