Skip to content

Commit 6719e7c

Browse files
committed
fix: corrected e2e test fails
1 parent 9431e5f commit 6719e7c

File tree

2 files changed

+72
-0
lines changed

2 files changed

+72
-0
lines changed

middleware.ts

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import { NextRequest, NextResponse } from 'next/server'
2+
3+
export function middleware(req: NextRequest) {
4+
const { pathname } = req.nextUrl
5+
6+
// Match only /news/<segment> (single segment)
7+
const match = pathname.match(/^\/news\/([^\/]+)$/)
8+
if (match) {
9+
const year = match[1]
10+
// Return 404 for non four-digit or out-of-range years
11+
if (!/^\d{4}$/.test(year)) {
12+
return new NextResponse('Not Found', { status: 404 })
13+
}
14+
const yearNum = parseInt(year, 10)
15+
if (yearNum < 2001 || yearNum > 2025) {
16+
return new NextResponse('Not Found', { status: 404 })
17+
}
18+
}
19+
20+
return NextResponse.next()
21+
}
22+
23+
export const config = {
24+
matcher: ['/news/:year*'],
25+
}
26+

src/test/middleware.test.ts

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import { describe, it, expect } from 'vitest'
2+
import { middleware } from '../../middleware'
3+
import type { NextRequest } from 'next/server'
4+
5+
// Helper to create a minimal NextRequest-like object for testing
6+
function mockRequest(pathname: string) {
7+
return { nextUrl: { pathname } } as unknown as NextRequest
8+
}
9+
10+
describe('middleware /news/:year validation', () => {
11+
it('allows valid year at lower bound (2001)', () => {
12+
const res = middleware(mockRequest('/news/2001'))
13+
expect(res.status).toBe(200)
14+
})
15+
16+
it('allows valid year at upper bound (2025)', () => {
17+
const res = middleware(mockRequest('/news/2025'))
18+
expect(res.status).toBe(200)
19+
})
20+
21+
it('returns 404 for year below range (1999)', () => {
22+
const res = middleware(mockRequest('/news/1999'))
23+
expect(res.status).toBe(404)
24+
})
25+
26+
it('returns 404 for year above range (2026)', () => {
27+
const res = middleware(mockRequest('/news/2026'))
28+
expect(res.status).toBe(404)
29+
})
30+
31+
it('returns 404 for non-numeric year (abcd)', () => {
32+
const res = middleware(mockRequest('/news/abcd'))
33+
expect(res.status).toBe(404)
34+
})
35+
36+
it('passes through for paths with extra segments (not single-segment match)', () => {
37+
const res = middleware(mockRequest('/news/2025/extra'))
38+
expect(res.status).toBe(200)
39+
})
40+
41+
it('passes through for non-news paths', () => {
42+
const res = middleware(mockRequest('/features'))
43+
expect(res.status).toBe(200)
44+
})
45+
})
46+

0 commit comments

Comments
 (0)