|
| 1 | +// Copyright 2025 Google LLC |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +import {getGoogleIdToken} from '../src/toolbox_core/authMethods'; |
| 16 | +import {GoogleAuth} from 'google-auth-library'; |
| 17 | + |
| 18 | +jest.mock('google-auth-library', () => ({GoogleAuth: jest.fn()})); |
| 19 | + |
| 20 | +describe('getGoogleIdToken', () => { |
| 21 | + const mockUrl = 'https://example.com'; |
| 22 | + const mockToken = 'mock-id-token'; |
| 23 | + |
| 24 | + let mockGetIdTokenClient: jest.Mock; |
| 25 | + let mockFetchIdToken: jest.Mock; |
| 26 | + |
| 27 | + beforeEach(() => { |
| 28 | + // Reset mocks before each test |
| 29 | + mockFetchIdToken = jest.fn().mockResolvedValue(mockToken); |
| 30 | + mockGetIdTokenClient = jest.fn().mockResolvedValue({ |
| 31 | + idTokenProvider: { |
| 32 | + fetchIdToken: mockFetchIdToken, |
| 33 | + }, |
| 34 | + }); |
| 35 | + (GoogleAuth as jest.MockedClass<typeof GoogleAuth>).mockImplementation( |
| 36 | + () => |
| 37 | + ({ |
| 38 | + getIdTokenClient: mockGetIdTokenClient, |
| 39 | + }) as unknown as GoogleAuth |
| 40 | + ); |
| 41 | + }); |
| 42 | + |
| 43 | + it('should return a Bearer token on successful fetch', async () => { |
| 44 | + const token = await getGoogleIdToken(mockUrl); |
| 45 | + expect(token).toBe(`Bearer ${mockToken}`); |
| 46 | + expect(GoogleAuth).toHaveBeenCalledTimes(1); |
| 47 | + expect(mockGetIdTokenClient).toHaveBeenCalledWith(mockUrl); |
| 48 | + expect(mockFetchIdToken).toHaveBeenCalledWith(mockUrl); |
| 49 | + }); |
| 50 | + |
| 51 | + it('should propagate errors from getIdTokenClient', async () => { |
| 52 | + const errorMessage = 'Failed to get ID token client'; |
| 53 | + mockGetIdTokenClient.mockRejectedValue(new Error(errorMessage)); |
| 54 | + |
| 55 | + await expect(getGoogleIdToken(mockUrl)).rejects.toThrow(errorMessage); |
| 56 | + }); |
| 57 | + |
| 58 | + it('should propagate errors from fetchIdToken', async () => { |
| 59 | + const errorMessage = 'Failed to fetch ID token'; |
| 60 | + mockFetchIdToken.mockRejectedValue(new Error(errorMessage)); |
| 61 | + |
| 62 | + await expect(getGoogleIdToken(mockUrl)).rejects.toThrow(errorMessage); |
| 63 | + }); |
| 64 | +}); |
0 commit comments