diff --git a/src/lib/util/extract-user.test.ts b/src/lib/util/extract-user.test.ts new file mode 100644 index 0000000000..85494876e1 --- /dev/null +++ b/src/lib/util/extract-user.test.ts @@ -0,0 +1,32 @@ +import { IUser } from '../server-impl'; +import { extractUsernameFromUser } from './extract-user'; + +describe('extractUsernameFromUser', () => { + test('Should return the email if it exists', () => { + const user = { + email: 'ratatoskr@yggdrasil.com', + username: 'ratatoskr', + } as IUser; + + expect(extractUsernameFromUser(user)).toBe(user.email); + }); + + test('Should return the username if it exists and email does not', () => { + const user = { + username: 'ratatoskr', + } as IUser; + + expect(extractUsernameFromUser(user)).toBe(user.username); + }); + + test('Should return "unknown" if neither email nor username exists', () => { + const user = {} as IUser; + + expect(extractUsernameFromUser(user)).toBe('unknown'); + }); + + test('Should return "unknown" if user is null', () => { + const user = null as unknown as IUser; + expect(extractUsernameFromUser(user)).toBe('unknown'); + }); +}); diff --git a/src/lib/util/extract-user.ts b/src/lib/util/extract-user.ts index 75f1e38089..84ba126ce5 100644 --- a/src/lib/util/extract-user.ts +++ b/src/lib/util/extract-user.ts @@ -1,7 +1,7 @@ import { IAuthRequest, IUser } from '../server-impl'; export function extractUsernameFromUser(user: IUser): string { - return user ? user.email || user.username : 'unknown'; + return user?.email || user?.username || 'unknown'; } export function extractUsername(req: IAuthRequest): string {