seo-generator-server/tests/_helpers/commonjs-bridge.js

41 lines
1.3 KiB
JavaScript

/**
* Bridge pour importer les modules CommonJS depuis les tests ES modules
*/
import { createRequire } from 'module';
import path from 'path';
import fs from 'fs';
const require = createRequire(import.meta.url);
const ROOT = process.cwd();
// ✅ CHARGEMENT .ENV AUTOMATIQUE POUR LES TESTS
const envPath = path.join(ROOT, '.env');
if (fs.existsSync(envPath) && !process.env._ENV_LOADED_BY_TESTS) {
const lines = fs.readFileSync(envPath, 'utf8').split(/\r?\n/);
for (const line of lines) {
const match = line.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*)\s*$/i);
if (match && !process.env[match[1]]) {
process.env[match[1]] = match[2].replace(/^"|"$/g, '');
}
}
process.env._ENV_LOADED_BY_TESTS = 'true';
}
export function requireCommonJS(modulePath) {
try {
const fullPath = path.join(ROOT, 'lib', `${modulePath}.js`);
// Clear require cache pour tests fraîches
delete require.cache[require.resolve(fullPath)];
return require(fullPath);
} catch (error) {
throw new Error(`Failed to require ${modulePath}: ${error.message}`);
}
}
export function mockModule(modulePath, mockExports) {
const fullPath = path.join(ROOT, 'lib', `${modulePath}.js`);
require.cache[require.resolve(fullPath)] = {
exports: mockExports,
loaded: true
};
}