|
| 1 | +import preAuthenticateJWT from '..' |
| 2 | + |
| 3 | +global.fetch = jest.fn() |
| 4 | + |
| 5 | +const mockFetchResponse = (body = {}, ok = true, status = 200) => { |
| 6 | + const fetchMock = global.fetch as jest.Mock |
| 7 | + fetchMock.mockResolvedValueOnce({ |
| 8 | + ok, |
| 9 | + status, |
| 10 | + json: () => Promise.resolve(body), |
| 11 | + headers: { |
| 12 | + get: () => 'application/json', |
| 13 | + }, |
| 14 | + }) |
| 15 | +} |
| 16 | + |
| 17 | +describe('preAuthenticateJWT', () => { |
| 18 | + beforeEach(() => { |
| 19 | + process.env.NEXT_PUBLIC_API_BASE_URL = 'http://localhost:3000' |
| 20 | + jest.clearAllMocks() |
| 21 | + }) |
| 22 | + |
| 23 | + it('should throw an error if no token is provided', async () => { |
| 24 | + await expect(preAuthenticateJWT()).rejects.toThrow('No token provided.') |
| 25 | + }) |
| 26 | + |
| 27 | + it('should call fetch with the correct URL and headers', async () => { |
| 28 | + const token = 'test-jwt-token' |
| 29 | + const expectedUrl = 'http://localhost:3000/auth/pre-auth/jwt' |
| 30 | + mockFetchResponse({ success: true }) |
| 31 | + |
| 32 | + await preAuthenticateJWT(token) |
| 33 | + |
| 34 | + expect(fetch).toHaveBeenCalledWith(expectedUrl, { |
| 35 | + method: 'POST', |
| 36 | + body: JSON.stringify({ token }), |
| 37 | + headers: { |
| 38 | + Accept: 'application/json', |
| 39 | + 'Content-Type': 'application/json', |
| 40 | + }, |
| 41 | + }) |
| 42 | + }) |
| 43 | + |
| 44 | + it('should return a response on successful pre-authentication', async () => { |
| 45 | + const responseData = { success: true, details: 'User authenticated.' } |
| 46 | + mockFetchResponse(responseData) |
| 47 | + |
| 48 | + const response = await preAuthenticateJWT('valid-jwt-token') |
| 49 | + |
| 50 | + expect(response).toEqual(responseData) |
| 51 | + }) |
| 52 | + |
| 53 | + it('should handle network or server errors gracefully', async () => { |
| 54 | + const errorMessage = 'Network error' |
| 55 | + const fetchMock = global.fetch as jest.Mock |
| 56 | + fetchMock.mockRejectedValueOnce(new Error(errorMessage)) |
| 57 | + |
| 58 | + await expect(preAuthenticateJWT('valid-jwt-token')).rejects.toThrow(errorMessage) |
| 59 | + }) |
| 60 | +}) |
0 commit comments