Some checks failed
Deploy / deploy (push) Has been cancelled
Full-stack web application for Telegram management - Frontend: Vue 3 + Vben Admin - Backend: NestJS - Features: User management, group broadcast, statistics 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
86 lines
2.4 KiB
JavaScript
86 lines
2.4 KiB
JavaScript
import { jest } from '@jest/globals';
|
|
import { globalRateLimiter, strictRateLimiter, dynamicRateLimiter } from '../../../../../services/api-gateway/src/middleware/rateLimiter.js';
|
|
|
|
// Mock Redis store
|
|
jest.mock('rate-limit-redis', () => ({
|
|
default: jest.fn(() => ({
|
|
increment: jest.fn(),
|
|
decrement: jest.fn(),
|
|
resetKey: jest.fn()
|
|
}))
|
|
}));
|
|
|
|
describe('Rate Limiter Middleware', () => {
|
|
let req, res, next;
|
|
|
|
beforeEach(() => {
|
|
req = {
|
|
ip: '127.0.0.1',
|
|
user: { id: 'user123', role: 'user' },
|
|
path: '/api/v1/test'
|
|
};
|
|
res = {
|
|
status: jest.fn(() => res),
|
|
json: jest.fn(() => res),
|
|
set: jest.fn(() => res)
|
|
};
|
|
next = jest.fn();
|
|
jest.clearAllMocks();
|
|
});
|
|
|
|
describe('globalRateLimiter', () => {
|
|
it('should allow request within rate limit', async () => {
|
|
// Mock the rate limiter to allow the request
|
|
const middleware = globalRateLimiter;
|
|
|
|
// Since globalRateLimiter is created by express-rate-limit,
|
|
// we need to test its configuration
|
|
expect(middleware).toBeDefined();
|
|
expect(typeof middleware).toBe('function');
|
|
});
|
|
|
|
it('should set rate limit headers', async () => {
|
|
// Test that rate limit headers are set correctly
|
|
res.setHeader = jest.fn();
|
|
|
|
// Mock a successful request
|
|
const mockRateLimitInfo = {
|
|
limit: 100,
|
|
current: 25,
|
|
remaining: 75,
|
|
resetTime: new Date(Date.now() + 60000)
|
|
};
|
|
|
|
// Test headers would be set by the middleware
|
|
expect(res.setHeader).not.toHaveBeenCalled(); // Initially not called
|
|
});
|
|
});
|
|
|
|
describe('strictRateLimiter', () => {
|
|
it('should have stricter limits than global', () => {
|
|
expect(strictRateLimiter).toBeDefined();
|
|
expect(typeof strictRateLimiter).toBe('function');
|
|
});
|
|
});
|
|
|
|
describe('dynamicRateLimiter', () => {
|
|
it('should apply different limits based on user role', async () => {
|
|
// Test for admin user
|
|
req.user.role = 'admin';
|
|
expect(dynamicRateLimiter).toBeDefined();
|
|
|
|
// Test for regular user
|
|
req.user.role = 'user';
|
|
expect(dynamicRateLimiter).toBeDefined();
|
|
|
|
// Test for viewer
|
|
req.user.role = 'viewer';
|
|
expect(dynamicRateLimiter).toBeDefined();
|
|
});
|
|
|
|
it('should apply default limits for unauthenticated users', async () => {
|
|
req.user = null;
|
|
expect(dynamicRateLimiter).toBeDefined();
|
|
});
|
|
});
|
|
}); |