import axios, { Axios, AxiosError, AxiosResponse } from 'axios'; import { expect } from 'chai'; import * as sinon from 'sinon'; import HTTP_STATUS_CODE from '../src/constants/httpStatusCode'; import AuthError from '../src/exceptions/authError'; import { ILoginParameters } from '../src/interfaces/ILoginParameters'; import { AuthService } from '../src/services/authService'; const data = { service: 'wallet', action: 'add', status: 'ACTIVE', }; const api_response = { data, status: 200, statusText: 'OK', headers: null, config: null, } as any as AxiosResponse; const parameters: ILoginParameters = { username: { value: 'test' }, password: { value: '123' } } as any as ILoginParameters; const auth_url = 'authenticate'; describe('Tests suite - Auth Service.', () => { afterEach('After each test', async () => { sinon.restore(); }); it('SUCCESS: Validate authorization and send to API', async () => { const body_response = { data: '123', }; sinon.stub(Axios.prototype, 'post').resolves(body_response); const auth_service = new AuthService(auth_url); const response = await auth_service.registerToken(parameters); expect(response.body).to.be.equal('123'); }); it('ERROR: Register token.', async () => { const register_token = new AuthService(auth_url); let response; try { sinon.stub(axios, 'post').resolves(api_response); response = await register_token.registerToken(parameters); } catch (err) { response = err; } expect(response.status).to.be.equal(500); }); it('ERROR - Validate authorization and send to API', async () => { const auth_service = new AuthService(auth_url); try { await auth_service.registerToken({ username: 'username', password: 'password' }); } catch (error) { expect(error.status).to.be.equal(HTTP_STATUS_CODE.INTERNAL_SERVER_ERROR); } }); it('ERROR - Validate authorization and send to API', async () => { const error_service = new AuthError({ response: { status: HTTP_STATUS_CODE.BAD_REQUEST } } as unknown as AxiosError); sinon.stub(AuthService.prototype, 'registerToken').rejects(error_service); const auth_service = new AuthService(auth_url); try { await auth_service.registerToken({ username: 'username', password: 'password' }); } catch (error) { expect(error.status).to.be.equal(HTTP_STATUS_CODE.BAD_REQUEST); } }); });