测试有哪几种
What are the different kinds of tests
一句话:按范围从小到大 ——单元 → 集成 → 端到端, 这就是「测试金字塔」:越往上越慢越脆,所以数量越少。
- 单元测试(unit)—— 测一个函数或一个组件, 依赖全部 mock。快、多、定位准。例:一个纯函数、 一个 React 组件的渲染。
- 集成测试(integration)—— 测几个模块协作是否正确, 可能真的连数据库或起一个测试服务器。 例:调一个 API 端点, 断言它真的写进了库。
- 端到端(E2E)——用真实浏览器走完整用户流程。 Playwright / Cypress。 最接近真实,也最慢最容易随机失败。
还会提到的几种:回归测试(防止改坏老功能)、 快照测试(比对渲染输出,容易变成「随手更新快照」的橡皮章)、 性能 / 压力测试、 可访问性测试、 冒烟测试(上线后快速验证主流程)。
Testing Library 的核心理念值得说:「像用户一样测试」—— 按可见文本和 role 查元素, 而不是按 class 名或组件内部结构。 这样重构内部实现测试不会碎。
会追问:「测试覆盖率要多少?」——不要给一个死数字。 正确回答是:覆盖率只说明「代码被执行过」, 不说明「断言是对的」。
这一点我可以给一个实测例子: Federation 那门课的源项目里, 六个端点全部 return null也能通过 3 个测试, node-subgraph 的 4 个「通过」里3 个是「空实现恰好满足断言」。所以「测试通过 ≠ 做对了」—— 比覆盖率数字更该关心的是断言够不够强。
In one line: smallest scope to largest — unit → integration → end-to-end. That is the testing pyramid: higher means slower and flakier, so you write fewer of them.
- Unit — one function or one component, everything else mocked. Fast, numerous, and precise about where the problem is. A pure function; a React component rendering.
- Integration — do a few modules work together, possibly against a real database or a test server. Call an API endpoint and assert the row really landed.
- End-to-end — a real browser walking a whole user journey. Playwright or Cypress. Closest to reality, and also the slowest and the most prone to random failure.
Others worth mentioning: regression tests (so old behaviour does not break), snapshot tests (comparing rendered output — which easily degrades into rubber-stamping “update snapshot”), performance and load tests, accessibility tests, and smoke tests for a quick check of the main flow after a deploy.
Testing Library’s core idea is worth stating: “test it the way a user uses it” — find elements by visible text and role, not by class name or internal component structure. Then refactoring the internals does not shatter the tests.
Follow-up: “What coverage number should you aim for?” — do not give a number. The right answer is that coverage tells you code was executed, not that the assertions are any good.
Here is a measured example: in the source project behind the Federation course, six endpoints that all just return null still passed 3 tests, and of the 4 passes in node-subgraph, 3 were an empty implementation happening to satisfy the assertion. So a green test does not mean you got it right — the strength of the assertions matters more than the coverage percentage.