import { Test, TestingModule } from '@nestjs/testing' import { datatype } from 'faker' import { factory } from '../../../test/factories' import { MockedModule } from '../../../test/types' import { UserNotFoundError } from '../../errors' import { Patient } from '../../models' import { PatientRepository } from '../../repositories' import { AuthenticationService } from './authentication.service' import { AuthTokenHelper } from './helpers' import { TokenValidatorService } from './token_validator.service' describe('TokenValidatorService', () => { let tokenValidatorService: TokenValidatorService let patientRepository: MockedModule let authenticationService: MockedModule beforeAll(async () => { patientRepository = { findByLogin: jest.fn(), } authenticationService = { getAccessToken: jest.fn(), } const app: TestingModule = await Test.createTestingModule({ providers: [ { provide: PatientRepository, useValue: patientRepository, }, { provide: AuthenticationService, useValue: authenticationService, }, TokenValidatorService, ], }).compile() tokenValidatorService = app.get(TokenValidatorService) }) afterEach(() => { jest.clearAllMocks() }) afterAll(() => { jest.restoreAllMocks() }) describe('#validatePatientToken', () => { const login = datatype.uuid() const token = datatype.uuid() const accessToken = datatype.uuid() let patient: Patient describe('when the patient exists', () => { const authTokenIsValidMock = jest.fn() let isValid: boolean beforeAll(async () => { AuthTokenHelper.authTokenIsValid = authTokenIsValidMock patient = await factory.build('patient') patientRepository.findByLogin.mockResolvedValue(patient) }) beforeEach(() => { authTokenIsValidMock.mockReturnValue(isValid) }) afterAll(() => { authTokenIsValidMock.mockReset() }) describe('and the token is valid', () => { beforeAll(() => { isValid = true authenticationService.getAccessToken.mockResolvedValue(accessToken) }) it('generates and return an access token', async () => { expect(await tokenValidatorService.validatePatientToken(login, token)).toEqual(accessToken) }) }) describe('and the token isn`t valid', () => { beforeAll(() => { isValid = false }) it('do nothing', async () => { expect(await tokenValidatorService.validatePatientToken(login, token)).toBeFalsy() }) }) }) describe('when the patient doest not exist', () => { beforeAll(() => { patientRepository.findByLogin.mockResolvedValue(null) }) it('throws an UserNotFoundError', async () => { await expect(tokenValidatorService.validatePatientToken(login, token)).rejects.toThrowError(UserNotFoundError) }) }) }) })