import fs from 'fs/promises'; import * as path from 'path'; import { Command } from 'commander'; // Mock markdownHtmlAgent to intercept calls in CLI handler jest.mock('../src/services/markdownHtmlAgent', () => { const actual = jest.requireActual('../src/services/markdownHtmlAgent'); return { ...actual, markdownHtmlAgent: jest.fn() }; }); import { cli, markdownHtmlAgent } from '../src/services/markdownHtmlAgent'; describe('markdownHtmlAgent CLI', () => { const inFile = '/tmp/input.md'; const outFile = '/tmp/output.html'; const opts = { title: 'T', date: '2022-02-02' }; beforeEach(() => jest.resetAllMocks()); it('exposes correct command and description', () => { expect(cli.command).toBe('markdown-to-html'); expect(cli.description).toMatch(/Convertit un fichier Markdown en HTML/); }); it('builder registers arguments and options', () => { const cmd = new Command(); cli.builder(cmd); const argsMeta = (cmd as any)._args as Array<{ _name: string }>; expect(argsMeta.map((a) => a._name)).toEqual(['markdownFile', 'outputFile']); const longs = cmd.options.map((o) => o.long); expect(longs).toEqual( expect.arrayContaining(['--title', '--date']) ); }); it('handler generates HTML and writes file on success', async () => { // Mock fs and markdownHtmlAgent jest.spyOn(fs, 'readFile').mockResolvedValue('md content'); (markdownHtmlAgent as jest.Mock).mockResolvedValue(''); const writeSpy = jest.spyOn(fs, 'writeFile').mockResolvedValue(); const logSpy = jest.spyOn(console, 'log').mockImplementation(() => {}); await cli.handler(inFile, outFile, opts); expect(fs.readFile).toHaveBeenCalledWith(inFile, 'utf-8'); expect(markdownHtmlAgent).toHaveBeenCalledWith({ title: opts.title, markdown: 'md content', date: opts.date, }); expect(writeSpy).toHaveBeenCalledWith(outFile, '', 'utf-8'); expect(logSpy).toHaveBeenCalledWith(`HTML généré: ${outFile}`); }); it('handler prints error and exits on failure', async () => { jest.spyOn(fs, 'readFile').mockRejectedValue(new Error('no input')); const errSpy = jest.spyOn(console, 'error').mockImplementation(() => {}); const exitSpy = jest.spyOn(process, 'exit').mockImplementation(((code?: number) => { throw new Error(`exit ${code}`); }) as any); await expect(cli.handler(inFile, outFile, opts)).rejects.toThrow('exit 1'); expect(errSpy).toHaveBeenCalledWith('Erreur génération HTML:', 'no input'); exitSpy.mockRestore(); }); });