Skip to content

Commit 2bbd2c7

Browse files
committed
test(middleware): add rate limit tests
1 parent e9da96e commit 2bbd2c7

1 file changed

Lines changed: 88 additions & 0 deletions

File tree

middleware.test.ts

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
import { beforeEach, describe, expect, it, vi } from 'vitest';
2+
import { NextRequest, NextResponse } from 'next/server';
3+
import { middleware } from './middleware';
4+
import { rateLimit } from '@/lib/rate-limit';
5+
6+
vi.mock('@/lib/rate-limit', () => ({
7+
rateLimit: vi.fn(),
8+
}));
9+
10+
describe('middleware', () => {
11+
beforeEach(() => {
12+
vi.clearAllMocks();
13+
});
14+
15+
it('calls NextResponse.next when rate limit succeeds', () => {
16+
vi.mocked(rateLimit).mockReturnValue({
17+
success: true,
18+
limit: 60,
19+
remaining: 59,
20+
reset: 123456789,
21+
});
22+
23+
const nextSpy = vi.spyOn(NextResponse, 'next');
24+
25+
const request = new NextRequest('http://localhost:3000/api/streak?user=octocat');
26+
middleware(request);
27+
28+
expect(nextSpy).toHaveBeenCalled();
29+
});
30+
31+
it('returns 429 when rate limit fails', () => {
32+
vi.mocked(rateLimit).mockReturnValue({
33+
success: false,
34+
limit: 60,
35+
remaining: 0,
36+
reset: 123456789,
37+
});
38+
39+
const request = new NextRequest('http://localhost:3000/api/streak?user=octocat');
40+
const response = middleware(request);
41+
42+
expect(response.status).toBe(429);
43+
});
44+
45+
it('returns too many requests error body when rate limit fails', async () => {
46+
vi.mocked(rateLimit).mockReturnValue({
47+
success: false,
48+
limit: 60,
49+
remaining: 0,
50+
reset: 123456789,
51+
});
52+
53+
const request = new NextRequest('http://localhost:3000/api/streak?user=octocat');
54+
const response = middleware(request);
55+
56+
await expect(response.json()).resolves.toEqual({
57+
error: 'Too many requests',
58+
});
59+
});
60+
61+
it('sets X-RateLimit-Limit header when rate limit succeeds', () => {
62+
vi.mocked(rateLimit).mockReturnValue({
63+
success: true,
64+
limit: 60,
65+
remaining: 59,
66+
reset: 123456789,
67+
});
68+
69+
const request = new NextRequest('http://localhost:3000/api/streak?user=octocat');
70+
const response = middleware(request);
71+
72+
expect(response.headers.get('X-RateLimit-Limit')).toBe('60');
73+
});
74+
75+
it('sets X-RateLimit-Remaining header when rate limit succeeds', () => {
76+
vi.mocked(rateLimit).mockReturnValue({
77+
success: true,
78+
limit: 60,
79+
remaining: 59,
80+
reset: 123456789,
81+
});
82+
83+
const request = new NextRequest('http://localhost:3000/api/streak?user=octocat');
84+
const response = middleware(request);
85+
86+
expect(response.headers.get('X-RateLimit-Remaining')).toBe('59');
87+
});
88+
});

0 commit comments

Comments
 (0)