-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.spec.ts
87 lines (67 loc) · 2.54 KB
/
middleware.spec.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import type { MockInstance } from 'vitest'
import { type NextRequest, NextResponse } from 'next/server'
import { mock } from 'vitest-mock-extended'
import type { AppRouteHandlerFnContext } from 'next-auth/lib/types'
import { cookies } from 'next/headers'
import type { ReadonlyRequestCookies } from 'next/dist/server/web/spec-extension/adapters/request-cookies'
import middleware from './middleware'
import { getServerUser } from '@app/auth'
vi.mock('next-auth', () => ({
default: vi.fn().mockReturnValue({
auth: vi.fn().mockImplementation((function_: never) => function_),
}),
}))
vi.mock('next/server')
vi.mock('next/headers')
vi.mock('@app/auth')
const cookiesFactoryMock = (value?: string) =>
({
get: vi.fn().mockReturnValue({
value,
}),
}) as unknown as ReadonlyRequestCookies
const requestFactoryMock = (pathname: string) =>
mock<NextRequest>({
nextUrl: {
pathname,
},
url: 'http://localhost:3000',
} as unknown as NextRequest)
describe('middleware', () => {
const userId = 'userId'
let redirectSpy: MockInstance
let cookiesSpy: MockInstance
beforeEach(() => {
redirectSpy = vi.mocked(NextResponse.redirect)
cookiesSpy = vi.mocked(cookies)
})
test('should redirect to profile page if user is logged in', async () => {
const requestMock = requestFactoryMock('/profile')
cookiesSpy.mockImplementation(() => cookiesFactoryMock(userId))
await middleware(requestMock, mock<AppRouteHandlerFnContext>())
expect(redirectSpy).toHaveBeenCalledWith(
new URL(`/profile/${userId}`, requestMock.url)
)
expect(cookiesSpy).toHaveBeenCalled()
})
test('should redirect to home page if user is not logged in', async () => {
const request = requestFactoryMock('/profile')
cookiesSpy.mockImplementation(cookiesFactoryMock)
await middleware(request, mock<AppRouteHandlerFnContext>())
expect(redirectSpy).toHaveBeenCalledWith(new URL('/', request.url))
expect(cookiesSpy).toHaveBeenCalled()
})
test('should redirect to disconnect route if user is logged in but no userId is found', async () => {
const request = requestFactoryMock('/')
const getServerUserSpy = vi
.mocked(getServerUser)
.mockResolvedValue({ name: 'John Doe' })
cookiesSpy.mockImplementation(cookiesFactoryMock)
await middleware(request, mock<AppRouteHandlerFnContext>())
expect(redirectSpy).toHaveBeenCalledWith(
new URL('/api/auth/disconnect', request.url)
)
expect(cookiesSpy).toHaveBeenCalled()
expect(getServerUserSpy).toHaveBeenCalled()
})
})