From 115394ac8ca8b66906cfeb44ffa32a8202d1dfb2 Mon Sep 17 00:00:00 2001 From: Ali BARIN Date: Mon, 30 Sep 2024 12:04:58 +0000 Subject: [PATCH] test(helpers/authentication): bring back applicable tests --- .../src/helpers/authentication.test.js | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 packages/backend/src/helpers/authentication.test.js diff --git a/packages/backend/src/helpers/authentication.test.js b/packages/backend/src/helpers/authentication.test.js new file mode 100644 index 00000000..1b5f1620 --- /dev/null +++ b/packages/backend/src/helpers/authentication.test.js @@ -0,0 +1,33 @@ +import { describe, it, expect } from 'vitest'; +import { isAuthenticated } from './authentication.js'; +import { createUser } from '../../test/factories/user.js'; +import createAuthTokenByUserId from '../helpers/create-auth-token-by-user-id.js'; + +describe('isAuthenticated', () => { + it('should return false if no token is provided', async () => { + const req = { headers: {} }; + expect(await isAuthenticated(req)).toBe(false); + }); + + it('should return false if token is invalid', async () => { + const req = { headers: { authorization: 'invalidToken' } }; + expect(await isAuthenticated(req)).toBe(false); + }); + + it('should return true if token is valid and there is a user', async () => { + const user = await createUser(); + const token = await createAuthTokenByUserId(user.id); + + const req = { headers: { authorization: token } }; + expect(await isAuthenticated(req)).toBe(true); + }); + + it('should return false if token is valid and but there is no user', async () => { + const user = await createUser(); + const token = await createAuthTokenByUserId(user.id); + await user.$query().delete(); + + const req = { headers: { authorization: token } }; + expect(await isAuthenticated(req)).toBe(false); + }); +});