'use strict'; const { app, mock } = require('egg-mock/bootstrap'); const createFakeRedis = require('../../utils/fake-redis'); describe('test/app/controller/health.test.js', () => { beforeEach(() => { mock(app, 'redis', createFakeRedis().client); }); it('MySQL 与 Redis 正常时返回 200', async () => { mock(app, 'model', { async authenticate() { return true; }, }); const res = await app.httpRequest().get('/health').expect(200); if (res.body.ok !== true) throw new Error('health 应为 ok'); if (res.body.dependencies.mysql.ok !== true) throw new Error('mysql 应可用'); if (res.body.dependencies.redis.ok !== true) throw new Error('redis 应可用'); }); it('MySQL 不可用时返回 503', async () => { mock(app, 'model', { async authenticate() { throw new Error("Access denied for user 'packservice'@'localhost'"); }, }); const res = await app.httpRequest().get('/health').expect(503); if (res.body.dependencies.mysql.ok !== false) throw new Error('mysql 应标记为不可用'); }); it('Redis 不可用时返回 503', async () => { mock(app, 'model', { async authenticate() { return true; }, }); mock(app, 'redis', { async ping() { throw new Error('NOAUTH Authentication required.'); }, }); const res = await app.httpRequest().get('/health').expect(503); if (res.body.ok !== false) throw new Error('health 应为 ok:false'); if (res.body.dependencies.redis.ok !== false) throw new Error('redis 应标记为不可用'); }); });