如何对“健康检查”做集成测试?
解读
在国内互联网公司的面试里,“健康检查”通常指微服务架构中的 /health 或 /ready 端点,用于 Kubernetes 存活探针(livenessProbe)与就绪探针(readinessProbe)。面试官问“如何做集成测试”,并不是让你写单元测试去 Mock 掉数据库,而是考察:
- 你是否理解“集成”二字——把真实依赖(MySQL、Redis、RabbitMQ、Consul、外部 HTTP 接口)全部拉起来;
- 能否用 Jest 快速编排一套“本地可重复、CI 可运行、不污染线上”的测试方案;
- 是否熟悉国内主流技术栈(Egg/Nest/SpringBoot + MySQL + Redis + Docker)以及阿里/腾讯/字节内部常用的测试约定(如必须输出统一 JSON、耗时 < 150 ms、失败时返回 503 并打 ERROR 日志)。
一句话:你要让 npm test 在 30 秒内把真实容器拉起,调一次 /health,断言返回体、状态码、耗时、日志、指标全通过,再优雅地回收资源。
知识点
- Jest 生命周期钩子:beforeAll、afterAll、beforeEach、afterEach,用于“全局一次性”与“用例级”资源申请与释放。
- jest-environment-node 与自定义 testEnvironment:在 Node 侧跑集成测试时,可继承 NodeEnvironment 做全局兜底清理。
- Testcontainers(Node 版):用 Dockerode 在测试开始时拉取官方镜像(mysql:8.0、redis:7-alpine),随机端口映射,结束后自动 rm -f,保证并发无端口冲突。
- 动态配置注入:通过 jest.config.js 的 globalSetup/globalTeardown 把容器连接串写入
process.env,业务代码零感知。 - 断言策略:
- 状态码:expect(response.status).toBe(200)
- 响应体:expect(body).toMatchObject({ status: 'UP', components: { db: 'UP', redis: 'UP' } })
- 耗时:expect(duration).toBeLessThan(150)
- 日志:使用 jest.spyOn(logger, 'error') 保证无意外错误日志
- 指标:如果接入了 Prometheus,可额外 GET /metrics 验证 health_check_total 计数器 +1
- 失败场景覆盖:手动 pause 容器(docker pause mysql)→ 调 /health → 期望 503 → 恢复容器 → 再次 200,验证自愈。
- 并发与缓存:Jest 默认并行,testcontainers 的 Reaper 会全局加锁,CI 中需加
--runInBand防止端口抢占。 - 国内镜像加速:在 globalSetup 里写入
process.env.DOCKER_REGISTRY = 'registry.npmmirror.com'解决 Docker Hub 拉取慢的问题。 - 覆盖率门禁:nyc 或 jest --coverage,要求分支覆盖率 90%,否则 CI 失败(阿里规约)。
答案
以下示例基于 NestJS + Jest + testcontainers,给出最小可运行方案,可直接放到 test/health.integration.spec.ts,npm test -- health.integration 即可。
# 安装依赖
npm i -D jest testcontainers mysql2 ioredis axios
// test/health.integration.spec.ts
import { GenericContainer } from 'testcontainers';
import axios from 'axios';
import * as path from 'path';
describe('Health Check Integration', () => {
let mysqlContainer;
let redisContainer;
let appPort;
let app;
beforeAll(async () => {
// 1. 拉起 MySQL
mysqlContainer = await new GenericContainer('mysql:8.0')
.withEnv('MYSQL_ROOT_PASSWORD', '123456')
.withEnv('MYSQL_DATABASE', 'demo')
.withExposedPorts(3306)
.start();
process.env.DB_HOST = mysqlContainer.getHost();
process.env.DB_PORT = mysqlContainer.getMappedPort(3306);
process.env.DB_USER = 'root';
process.env.DB_PASS = '123456';
// 2. 拉起 Redis
redisContainer = await new GenericContainer('redis:7-alpine')
.withExposedPorts(6379)
.start();
process.env.REDIS_HOST = redisContainer.getHost();
process.env.REDIS_PORT = redisContainer.getMappedPort(6379);
// 3. 启动 Nest 应用(随机端口)
const { NestFactory } = require('@nestjs/core');
const { AppModule } = require('../src/app.module');
app = await NestFactory.create(AppModule);
await app.listen(0);
appPort = app.getHttpServer().address().port;
}, 120000); // 两分钟超时,防止镜像拉取慢
afterAll(async () => {
await app.close();
await mysqlContainer.stop();
await redisContainer.stop();
});
it('should return 200 when all components are UP', async () => {
const start = Date.now();
const res = await axios.get(`http://localhost:${appPort}/health`);
const duration = Date.now() - start;
expect(res.status).toBe(200);
expect(res.data).toMatchObject({
status: 'UP',
components: {
db: { status: 'UP' },
redis: { status: 'UP' },
},
});
expect(duration).toBeLessThan(150);
});
it('should return 503 when mysql is down', async () => {
await mysqlContainer.stop();
try {
const res = await axios.get(`http://localhost:${appPort}/health`);
expect(res.status).toBe(503);
expect(res.data.components.db.status).toBe('DOWN');
} finally {
// 恢复容器,避免污染后续测试
await mysqlContainer.restart();
}
});
});
CI 脚本(GitHub Actions / 阿里云效 / 腾讯云 CI 通用):
- name: Run integration tests
run: |
npm run test:integration -- --runInBand --forceExit
env:
DOCKER_REGISTRY: registry.npmmirror.com
拓展思考
- 多环境复用:测试通过后再把同一份镜像推到预发,用 Kubernetes 的 helm test 做二次验收,实现“测试即部署”。
- 混沌工程:在 Jest 里集成 chaos-mesh 的 Node SDK,随机杀容器、打高网络延迟,验证健康检查是否 5 秒内准确降级。
- 性能基线:把耗时结果写入
.perf.json,下次 CI 用 jest-expect-performance 做回归,防止依赖增多导致探针超时。 - 安全合规:国内金融项目要求敏感字段脱敏,可在 /health 返回前用 jest 快照测试比对 JSON 结构,确保无内网 IP、密码泄露。
- 低成本替代:如果公司 CI 资源紧张,可用 GitHub 的 mysql-service、redis-service 语法代替 testcontainers,但需接受端口固定、并发冲突的风险,面试时可作为“降级方案”主动提出,体现权衡能力。