|
| 1 | +import { describe, it, expect, vi } from 'vitest'; |
| 2 | +import { ApiChaosMonkey } from './apiChaosMonkey'; |
| 3 | + |
| 4 | +describe('ApiChaosMonkey', () => { |
| 5 | + it('should not drop connection if disabled', () => { |
| 6 | + const chaosMonkey = new ApiChaosMonkey({ dropProbability: 1.0, enabled: false }); |
| 7 | + const req = {}; |
| 8 | + const res = { status: vi.fn().mockReturnThis(), json: vi.fn() }; |
| 9 | + const next = vi.fn(); |
| 10 | + |
| 11 | + chaosMonkey.middleware()(req, res, next); |
| 12 | + expect(next).toHaveBeenCalled(); |
| 13 | + expect(res.status).not.toHaveBeenCalled(); |
| 14 | + }); |
| 15 | + |
| 16 | + it('should drop connection based on probability', () => { |
| 17 | + // Math.random will return 0.1, which is < 0.5, so it drops |
| 18 | + vi.spyOn(Math, 'random').mockReturnValue(0.1); |
| 19 | + const chaosMonkey = new ApiChaosMonkey({ dropProbability: 0.5, enabled: true }); |
| 20 | + |
| 21 | + const req = {}; |
| 22 | + const res = { status: vi.fn().mockReturnThis(), json: vi.fn() }; |
| 23 | + const next = vi.fn(); |
| 24 | + |
| 25 | + chaosMonkey.middleware()(req, res, next); |
| 26 | + expect(next).not.toHaveBeenCalled(); |
| 27 | + expect(res.status).toHaveBeenCalledWith(503); |
| 28 | + expect(res.json).toHaveBeenCalledWith({ error: 'Service Unavailable - Chaos Monkey Intervention' }); |
| 29 | + |
| 30 | + vi.restoreAllMocks(); |
| 31 | + }); |
| 32 | + |
| 33 | + it('should pass connection if probability not met', () => { |
| 34 | + // Math.random will return 0.9, which is > 0.5, so it passes |
| 35 | + vi.spyOn(Math, 'random').mockReturnValue(0.9); |
| 36 | + const chaosMonkey = new ApiChaosMonkey({ dropProbability: 0.5, enabled: true }); |
| 37 | + |
| 38 | + const req = {}; |
| 39 | + const res = { status: vi.fn().mockReturnThis(), json: vi.fn() }; |
| 40 | + const next = vi.fn(); |
| 41 | + |
| 42 | + chaosMonkey.middleware()(req, res, next); |
| 43 | + expect(next).toHaveBeenCalled(); |
| 44 | + expect(res.status).not.toHaveBeenCalled(); |
| 45 | + |
| 46 | + vi.restoreAllMocks(); |
| 47 | + }); |
| 48 | +}); |
0 commit comments