|
| 1 | +import { describe, expect, test } from 'vitest' |
| 2 | +import type { Response } from 'express' |
| 3 | + |
| 4 | +import trailingSlashes from '@/frame/middleware/trailing-slashes' |
| 5 | +import { safeRedirectUrl } from '@/frame/middleware/safe-redirect' |
| 6 | +import type { ExtendedRequest } from '@/types' |
| 7 | + |
| 8 | +function run(url: string) { |
| 9 | + const req = { method: 'GET', url } as ExtendedRequest |
| 10 | + const headers: Record<string, string> = {} |
| 11 | + const result: { status?: number; location?: string; nextCalled: boolean } = { |
| 12 | + nextCalled: false, |
| 13 | + } |
| 14 | + const res = { |
| 15 | + set(key: string, value: string) { |
| 16 | + headers[key.toLowerCase()] = value |
| 17 | + return this |
| 18 | + }, |
| 19 | + hasHeader(key: string) { |
| 20 | + return key.toLowerCase() in headers |
| 21 | + }, |
| 22 | + safeRedirect(status: number, location: string) { |
| 23 | + result.status = status |
| 24 | + result.location = safeRedirectUrl(location) |
| 25 | + }, |
| 26 | + } as unknown as Response |
| 27 | + trailingSlashes(req, res, () => { |
| 28 | + result.nextCalled = true |
| 29 | + }) |
| 30 | + return { ...result, headers } |
| 31 | +} |
| 32 | + |
| 33 | +describe('trailingSlashes middleware', () => { |
| 34 | + test('redirects a path of only slashes to the homepage', () => { |
| 35 | + const result = run('//') |
| 36 | + expect(result.status).toBe(301) |
| 37 | + expect(result.location).toBe('/') |
| 38 | + expect(result.headers['cache-control']).toMatch(/max-age=\d+/) |
| 39 | + }) |
| 40 | + |
| 41 | + test('keeps the query string when redirecting a path of only slashes', () => { |
| 42 | + const result = run('//?foo=1') |
| 43 | + expect(result.status).toBe(301) |
| 44 | + expect(result.location).toBe('/?foo=1') |
| 45 | + }) |
| 46 | + |
| 47 | + test('keeps double slashes inside query values', () => { |
| 48 | + expect(run('//?next=https://github.com').location).toBe('/?next=https://github.com') |
| 49 | + expect(run('/en//search/?query=a//b').location).toBe('/en/search?query=a//b') |
| 50 | + }) |
| 51 | + |
| 52 | + test('removes a trailing slash and keeps the query string', () => { |
| 53 | + const result = run('/foo/?a=1') |
| 54 | + expect(result.status).toBe(301) |
| 55 | + expect(result.location).toBe('/foo?a=1') |
| 56 | + }) |
| 57 | + |
| 58 | + test('removes trailing double slashes', () => { |
| 59 | + const result = run('/en//') |
| 60 | + expect(result.status).toBe(301) |
| 61 | + expect(result.location).toBe('/en') |
| 62 | + }) |
| 63 | + |
| 64 | + test('calls next for the homepage', () => { |
| 65 | + const result = run('/') |
| 66 | + expect(result.nextCalled).toBe(true) |
| 67 | + expect(result.status).toBeUndefined() |
| 68 | + }) |
| 69 | +}) |
0 commit comments