import * as pem from 'pem' import * as http from 'http' import * as https from 'https' import { app, mockedAuthResponse } from './SAS_server_app' import { ServerType } from '@sasjs/utils' import SASjs from '../SASjs' import * as axiosModules from '../utils/createAxiosInstance' import { LoginRequiredError, AuthorizeError, NotFoundError, InternalServerError } from '../types/errors' import { prefixMessage } from '@sasjs/utils/error' import { RequestClient } from '../request/RequestClient' const axiosActual = jest.requireActual('axios') jest .spyOn(axiosModules, 'createAxiosInstance') .mockImplementation((baseURL: string, httpsAgent?: https.Agent) => axiosActual.create({ baseURL, httpsAgent }) ) const PORT = 8000 const SERVER_URL = `https://localhost:${PORT}/` const ERROR_MESSAGES = { selfSigned: 'self signed certificate', CCA: 'unable to verify the first certificate' } const incorrectAuthCodeErr = { error: 'unauthorized', error_description: 'Bad credentials' } describe('RequestClient', () => { let server: http.Server const adapter = new SASjs({ serverUrl: `http://localhost:${PORT}/`, serverType: ServerType.SasViya }) beforeAll(async () => { await new Promise((resolve: any, reject: any) => { server = app .listen(PORT, () => resolve()) .on('error', (err: any) => reject(err)) }) }) afterAll(() => { server.close() }) it('should response the POST method', async () => { const authResponse = await adapter.getAccessToken( 'clientId', 'clientSecret', 'authCode' ) expect(authResponse.access_token).toBe(mockedAuthResponse.access_token) }) it('should response the POST method with Unauthorized', async () => { await expect( adapter.getAccessToken('clientId', 'clientSecret', 'incorrect') ).rejects.toEqual( prefixMessage( new LoginRequiredError(incorrectAuthCodeErr), 'Error while getting access token. ' ) ) }) describe('handleError', () => { const requestClient = new RequestClient('https://localhost:8009') const randomError = 'some error' it('should throw an error if could not get confirmUrl', async () => { const authError = new AuthorizeError('message', 'confirm_url') jest .spyOn(requestClient['httpClient'], 'get') .mockImplementation(() => Promise.reject(randomError)) await expect( requestClient['handleError'](authError, () => {}) ).rejects.toEqual(`Error while getting error confirmUrl. ${randomError}`) }) it('should throw an error if authorize form is required', async () => { const authError = new AuthorizeError('message', 'confirm_url') jest .spyOn(requestClient['httpClient'], 'get') .mockImplementation(() => Promise.resolve({ data: '