// Mock FS to control certificate presence jest.mock('fs', () => ({ existsSync: jest.fn(), readFileSync: jest.fn(), })); // Mock axios module to spy on create calls jest.mock('axios', () => { const mockAxios: any = jest.fn(); mockAxios.create = jest.fn(); return mockAxios; }); import fs from 'fs'; import * as https from 'https'; import axios, { AxiosInstance } from 'axios'; import { GitlabClient } from '../src/services/gitlabClient'; describe('GitlabClient', () => { const baseUrl = 'http://gitlab.example.com'; const apiUrl = `${baseUrl}/api/v4`; const mockExists = fs.existsSync as jest.Mock; const mockRead = fs.readFileSync as jest.Mock; const mockCreate = (axios as any).create as jest.Mock; beforeEach(() => jest.resetAllMocks()); it('throws if token is empty', () => { expect(() => new GitlabClient({ token: '', url: baseUrl, workDir: '/tmp' })).toThrow( 'Le jeton GitLab est requis pour GitlabClient' ); }); it('uses global axios when no TLS certs present', () => { mockExists.mockReturnValue(false); const client = new GitlabClient({ token: 'tok', url: baseUrl, workDir: '/tmp' }); expect(client.instance).toBe(axios); expect(mockCreate).not.toHaveBeenCalled(); }); it('uses axios.create with httpsAgent when certs are present', () => { mockExists.mockReturnValue(true); mockRead.mockReturnValue(Buffer.from('data')); const fakeInstance = { get: jest.fn(), post: jest.fn(), defaults: { baseURL: apiUrl } } as unknown as AxiosInstance; mockCreate.mockReturnValue(fakeInstance); const client = new GitlabClient({ token: 'tok', url: baseUrl, workDir: '/tmp' }); expect(mockCreate).toHaveBeenCalledWith({ baseURL: apiUrl, headers: { 'PRIVATE-TOKEN': 'tok' }, httpsAgent: expect.any(https.Agent), }); expect(client.instance).toBe(fakeInstance); }); it('falls back to global axios if axios.create throws', () => { mockExists.mockReturnValue(true); mockRead.mockReturnValue(Buffer.from('data')); mockCreate.mockImplementation(() => { throw new Error('fail'); }); const client = new GitlabClient({ token: 'tok', url: baseUrl, workDir: '/tmp' }); expect(client.instance).toBe(axios); }); it('falls back to global axios if axios.create returns invalid object', () => { mockExists.mockReturnValue(true); mockRead.mockReturnValue(Buffer.from('data')); mockCreate.mockReturnValue({} as AxiosInstance); const client = new GitlabClient({ token: 'tok', url: baseUrl, workDir: '/tmp' }); expect(client.instance).toBe(axios); }); });