-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpreAuthenticateJWT.test.ts
60 lines (48 loc) · 1.71 KB
/
preAuthenticateJWT.test.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
import preAuthenticateJWT from '..'
global.fetch = jest.fn()
const mockFetchResponse = (body = {}, ok = true, status = 200) => {
const fetchMock = global.fetch as jest.Mock
fetchMock.mockResolvedValueOnce({
ok,
status,
json: () => Promise.resolve(body),
headers: {
get: () => 'application/json',
},
})
}
describe('preAuthenticateJWT', () => {
beforeEach(() => {
process.env.NEXT_PUBLIC_API_BASE_URL = 'http://localhost:3000'
jest.clearAllMocks()
})
it('should throw an error if no token is provided', async () => {
await expect(preAuthenticateJWT()).rejects.toThrow('No token provided.')
})
it('should call fetch with the correct URL and headers', async () => {
const token = 'test-jwt-token'
const expectedUrl = 'http://localhost:3000/auth/pre-auth/jwt'
mockFetchResponse({ success: true })
await preAuthenticateJWT(token)
expect(fetch).toHaveBeenCalledWith(expectedUrl, {
method: 'POST',
body: JSON.stringify({ token }),
cache: 'no-store',
headers: {
'Content-Type': 'application/json',
},
})
})
it('should return a response on successful pre-authentication', async () => {
const responseData = { success: true, details: 'User authenticated.' }
mockFetchResponse(responseData)
const response = await preAuthenticateJWT('valid-jwt-token')
expect(response).toEqual(responseData)
})
it('should handle network or server errors gracefully', async () => {
const errorMessage = 'Network error'
const fetchMock = global.fetch as jest.Mock
fetchMock.mockRejectedValueOnce(new Error(errorMessage))
await expect(preAuthenticateJWT('valid-jwt-token')).rejects.toThrow(errorMessage)
})
})