|
| 1 | +import { parseIdToken } from '../parseIdToken'; |
| 2 | +import { jwtDecode } from 'jwt-decode'; |
| 3 | + |
| 4 | +jest.mock('jwt-decode'); |
| 5 | + |
| 6 | +describe('parseIdToken', () => { |
| 7 | + const mockJwtDecode = jwtDecode as jest.Mock; |
| 8 | + |
| 9 | + beforeEach(() => { |
| 10 | + jest.clearAllMocks(); |
| 11 | + }); |
| 12 | + |
| 13 | + it('should return a User with decoded profile claims', () => { |
| 14 | + mockJwtDecode.mockReturnValue({ |
| 15 | + sub: 'auth0|123', |
| 16 | + name: 'Jane Doe', |
| 17 | + email: 'jane@example.com', |
| 18 | + email_verified: true, |
| 19 | + given_name: 'Jane', |
| 20 | + family_name: 'Doe', |
| 21 | + }); |
| 22 | + |
| 23 | + const user = parseIdToken('mock-id-token'); |
| 24 | + |
| 25 | + expect(user.sub).toBe('auth0|123'); |
| 26 | + expect(user.name).toBe('Jane Doe'); |
| 27 | + expect(user.email).toBe('jane@example.com'); |
| 28 | + expect(user.emailVerified).toBe(true); |
| 29 | + expect(user.givenName).toBe('Jane'); |
| 30 | + expect(user.familyName).toBe('Doe'); |
| 31 | + }); |
| 32 | + |
| 33 | + it('should exclude protocol claims', () => { |
| 34 | + mockJwtDecode.mockReturnValue({ |
| 35 | + sub: 'auth0|123', |
| 36 | + iss: 'https://tenant.auth0.com/', |
| 37 | + aud: 'client-id', |
| 38 | + exp: 9999999999, |
| 39 | + iat: 1000000000, |
| 40 | + }); |
| 41 | + |
| 42 | + const user = parseIdToken('mock-id-token'); |
| 43 | + |
| 44 | + expect(user.sub).toBe('auth0|123'); |
| 45 | + expect((user as any).iss).toBeUndefined(); |
| 46 | + expect((user as any).aud).toBeUndefined(); |
| 47 | + expect((user as any).exp).toBeUndefined(); |
| 48 | + expect((user as any).iat).toBeUndefined(); |
| 49 | + }); |
| 50 | + |
| 51 | + it('should throw if the token is missing the sub claim', () => { |
| 52 | + mockJwtDecode.mockReturnValue({ |
| 53 | + name: 'No Sub', |
| 54 | + email: 'nosub@example.com', |
| 55 | + }); |
| 56 | + |
| 57 | + expect(() => parseIdToken('bad-token')).toThrow( |
| 58 | + 'ID token is missing the required "sub" claim.' |
| 59 | + ); |
| 60 | + }); |
| 61 | +}); |
0 commit comments