"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const CommonFunctions = __importStar(require("../../src/lib/common-functions/common-functions"));
const fs = __importStar(require("fs"));
const fse = __importStar(require("fs-extra"));
const generateReport = __importStar(require("../../src/lib/generate-report/generate-report"));
const os = __importStar(require("os"));
const path = __importStar(require("path"));
const chai_1 = require("chai");
const chai_fs_1 = __importDefault(require("chai-fs"));
const axios_1 = __importDefault(require("axios"));
const sinon_1 = __importDefault(require("sinon"));
(0, chai_1.use)(chai_fs_1.default);
const readDirAsync = fs.promises.readdir;
const statAsync = fs.promises.stat;
describe('GenerateReport.ts', () => {
    const getReportPathInTempFolder = async () => {
        const tempDir = path.join(os.tmpdir(), 'cucumber-html-report-generator/');
        const foldersInTempDir = await readDirAsync(tempDir);
        const stats = await Promise.all(foldersInTempDir.map(async (folder) => {
            const stat = await statAsync(path.join(tempDir, folder));
            return { folder: tempDir + folder, stat };
        }));
        return stats.sort((firstStats, secondStats) => secondStats.stat.mtime.getTime() - firstStats.stat.mtime.getTime())[0].folder;
    };
    describe('Happy flows', () => {
        it('should create a report from the merged json files with metadata', async () => {
            // Given
            const reportPath = `${path.resolve('./')}/.tmp/unit/report01`;
            await CommonFunctions.emptyFolder(reportPath);
            const featuresFolder = path.resolve(reportPath, 'features/');
            await fse.mkdir(featuresFolder);
            const options = {
                openReportInBrowser: false,
                reportPath,
                showExecutionTime: true,
                customStyle: `${path.resolve('./')}/src/resources/templates/css/style-dark-theme.css`,
                useCDN: false,
                featuresFolder: `${path.resolve('./')}/test/unit/data/features/correct/`,
                jsonDir: `${path.resolve('./')}/test/unit/data/cucumber-report-jsons/`,
                saveCollectedJSON: true,
                saveEnrichedJSON: true,
                saveReportInMongoDb: false,
                reportMetadataTitle: 'Additional Data',
                reportMetadata: [
                    { name: 'Project', value: 'custom project' },
                    { name: 'Release', value: '1.2.3' },
                    { name: 'Cycle', value: '2' },
                    { name: 'Execution Start Date', value: '2021-03-26 14:01' },
                    { name: 'Execution End Date', value: '2021-03-26 16:05' }
                ]
            };
            // When
            await generateReport.generate(options);
            // Then
            (0, chai_1.expect)(await fse.pathExists(path.join(reportPath, 'index.html'))).to.equal(true);
            (0, chai_1.expect)(await fse.pathExists(path.join(reportPath, 'merged-output.json'))).to.equal(true);
            (0, chai_1.expect)(await fse.pathExists(path.join(reportPath, 'enriched-output.json'))).to.equal(true);
        });
        it('should create a report from the merged json files without metadata', async () => {
            // Given
            const options = {
                disableLog: true,
                navigateToFeatureIfThereIsOnlyOne: true,
                showExecutionTime: false,
                overrideStyle: `${path.resolve('./')}/src/resources/templates/css/style-dark-theme.css`,
                theme: 'Light',
                useCDN: true,
                saveEnrichedJSON: false,
                jsonDir: `${path.resolve('./')}/test/unit/data/cucumber-report-jsons`
            };
            // When
            await generateReport.generate(options);
            // Then
            const reportPath = await getReportPathInTempFolder();
            (0, chai_1.expect)((path.join(reportPath, 'index.html'))).to.be.a.file();
            sinon_1.default.restore();
        });
        it('should create a report from a json file without parameters', async () => {
            // Given
            const jsonFile = path.resolve(path.resolve('./'), './test/unit/data/enriched-joined-cucumber-jsons/enriched-output1.json');
            const reportSaved = (await CommonFunctions.readJsonFile(jsonFile));
            // When
            await generateReport.generateHtmlReport(undefined, reportSaved);
            // Then
            const reportPath = await getReportPathInTempFolder();
            (0, chai_1.expect)((path.join(reportPath, 'index.html'))).to.be.a.file();
        });
        it('should call to inserReport api', async () => {
            // Given
            const options = {
                disableLog: true,
                navigateToFeatureIfThereIsOnlyOne: false,
                openReportInBrowser: false,
                showExecutionTime: false,
                reportTitle: 'New report',
                // overrideStyle: `${path.resolve( './' )}/src/resources/templates/css/style-light-theme.css`,
                theme: 'Light',
                useCDN: true,
                saveEnrichedJSON: false,
                saveReportInMongoDb: true,
                mongooseServerUrl: 'http://localhost:3000',
                jsonDir: `${path.resolve('./')}/test/unit/data/cucumber-report-jsons`
            };
            // When
            const spy = sinon_1.default.stub(axios_1.default, 'post').resolves(Promise.resolve({ data: { reportId: '609c40e971b5b53a1965cec1' } }));
            await generateReport.generate(options);
            // Then
            (0, chai_1.expect)(spy.called);
            (0, chai_1.expect)(await generateReport.generate(options)).equal('609c40e971b5b53a1965cec1');
            sinon_1.default.restore();
        });
    });
    describe('failures', () => {
        it('should throw an error when no options are provided', async () => {
            // Given
            const options = null;
            // When
            await generateReport.generate(options).catch((error) => {
                // Then
                (0, chai_1.expect)(error.message).to.equal('Options need to be provided.');
            });
        });
        it('should throw an error when the json dir si not provided', async () => {
            // Given
            const reportPath = `${path.resolve('./')}/.tmp/unit/reports/report02/`;
            const options = {
                reportPath,
                jsonDir: '',
                reportMetadata: [
                    { name: 'browser', value: 'chrome 81' }
                ],
                saveEnrichedJSON: false,
                saveReportInMongoDb: true
            };
            // When
            await generateReport.generate(options).catch((error) => {
                // Then
                (0, chai_1.expect)(error.message).to.equal(`The path provided: '${options.jsonDir}' is invalid`);
            });
        });
        it('should throw an error when the report folder is invalid', async () => {
            // Given
            const reportPath = '/home/user1/test/test2';
            const options = {
                disableLog: true,
                navigateToFeatureIfThereIsOnlyOne: false,
                reportPath,
                jsonDir: `${path.resolve('./')}/test/unit/data/cucumber-report-jsons`,
                reportMetadata: [
                    { name: 'browser', value: 'chrome 81' }
                ],
            };
            // When
            await generateReport.generate(options).catch((error) => {
                // Then
                (0, chai_1.expect)(error.message).to.equal(`The path provided: '${options.reportPath}' is invalid`);
            });
        });
        it('should throw an error when the features folder is invalid', async () => {
            // Given
            const featuresFolder = '/home/user1/test/test2';
            const options = {
                disableLog: true,
                navigateToFeatureIfThereIsOnlyOne: false,
                featuresFolder,
                jsonDir: `${path.resolve('./')}/test/unit/data/cucumber-report-jsons`,
                reportMetadata: [
                    { name: 'browser', value: 'chrome 81' }
                ],
            };
            // When
            await generateReport.generate(options).catch((error) => {
                // Then
                (0, chai_1.expect)(error.message).to.equal(`The path provided: '${options.featuresFolder}' is invalid`);
            });
        });
        it('should throw an error when the json folder does not exist', async () => {
            // Given
            const options = {
                disableLog: true,
                navigateToFeatureIfThereIsOnlyOne: false,
                jsonDir: './invalid-folder',
                reportMetadata: [
                    { name: 'browser', value: 'chrome 81' }
                ],
            };
            // When
            await generateReport.generate(options).catch((error) => {
                // Then
                (0, chai_1.expect)(error.message).to.equal(`The path provided: '${options.jsonDir}' is invalid`);
            });
        });
    });
});
//# sourceMappingURL=generate-report-spec.js.map