import { Patient } from '../../../models' import { factory } from '../../../../test/factories/patient.factory' import { AuthTokenHelper, AuthToken, USER_HAS_NOT_TOKEN, INVALID_TOKEN, USERS_TOKEN_EXPIRED } from './auth.token.helper' describe('AuthTokenHelper', () => { describe('.authTokenIsValid', () => { let patient: Patient beforeEach(async () => { patient = await factory.build('patient') }) describe('when there is not a token', () => { beforeEach(() => { jest.spyOn(Patient.prototype, 'hasAuthToken').mockImplementationOnce(() => false) }) it('throws an not found http exception', () => { expect(() => AuthTokenHelper.authTokenIsValid(patient, '13323')).toThrow(USER_HAS_NOT_TOKEN) }) }) describe('when there is an expired token', () => { beforeEach(() => { jest.spyOn(Patient.prototype, 'hasAuthToken').mockImplementationOnce(() => true) jest.spyOn(Patient.prototype, 'hasExpiredAuthToken').mockImplementationOnce(() => true) }) it('throws an unauthorized http exception', () => { expect(() => AuthTokenHelper.authTokenIsValid(patient, '13323')).toThrow(USERS_TOKEN_EXPIRED) }) }) describe('when there is a valid token', () => { let authToken: AuthToken beforeEach(() => { authToken = AuthTokenHelper.buildAuthToken() patient.setAuthToken(authToken.encryptedCode) }) it('returns true if the token is correct', () => { expect(AuthTokenHelper.authTokenIsValid(patient, authToken.code)).toBeTruthy() }) it('throws an unauthorized http exception with a invalid token', () => { expect(() => AuthTokenHelper.authTokenIsValid(patient, '13323')).toThrow(INVALID_TOKEN) }) }) }) describe('.buildAuthToken', () => { it('returns an auth code', () => { const authToken = AuthTokenHelper.buildAuthToken() expect(authToken).toEqual( expect.objectContaining({ code: expect.any(String), encryptedCode: expect.any(String), }), ) }) describe('when code is given', () => { const code = '01234' it('returns the same code', () => { const authToken = AuthTokenHelper.buildAuthToken(code) expect(authToken).toEqual({ code, encryptedCode: expect.any(String), }) }) it('returns a valid encryptedCode', () => { const authToken = AuthTokenHelper.buildAuthToken(code) expect(AuthTokenHelper['tokenMatch'](code, authToken.encryptedCode)).toBeTruthy() }) }) }) })