/**
* Fixture loading utilities for tests
*/
import * as fs from 'fs';
import * as path from 'path';
import { fileURLToPath } from 'url';
// Get directory path for ES modules
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
/**
* Base path to fixtures directory
*/
const FIXTURES_DIR = path.join(__dirname, '../fixtures');
/**
* Load a specific fixture by name
*
* @param filename - Fixture file name (e.g., 'companies.json')
* @param key - Optional key to load specific entry from fixture
* @returns Parsed fixture data
*
* @example
* // Load entire fixture file
* const companies = loadFixture('companies.json');
*
* @example
* // Load specific entry
* const acme = loadFixture('companies.json', 'acme-corp');
*/
export function loadFixture<T = any>(filename: string, key?: string): T {
const fixturePath = path.join(FIXTURES_DIR, filename);
if (!fs.existsSync(fixturePath)) {
throw new Error(`Fixture file not found: ${filename}`);
}
const content = fs.readFileSync(fixturePath, 'utf-8');
const data = JSON.parse(content);
if (key) {
if (!(key in data)) {
throw new Error(`Fixture key "${key}" not found in ${filename}`);
}
return data[key] as T;
}
return data as T;
}
/**
* Load all entries from a fixture file
*
* @param filename - Fixture file name (e.g., 'companies.json')
* @returns Object with all fixture entries
*
* @example
* const allCompanies = loadAllFixtures('companies.json');
* // { "acme-corp": {...}, "tech-startup": {...} }
*/
export function loadAllFixtures<T = Record<string, any>>(filename: string): T {
return loadFixture<T>(filename);
}
/**
* Check if a fixture file exists
*
* @param filename - Fixture file name
* @returns True if fixture exists
*/
export function hasFixture(filename: string): boolean {
const fixturePath = path.join(FIXTURES_DIR, filename);
return fs.existsSync(fixturePath);
}
/**
* List all available fixture files
*
* @returns Array of fixture file names
*/
export function listFixtures(): string[] {
if (!fs.existsSync(FIXTURES_DIR)) {
return [];
}
return fs
.readdirSync(FIXTURES_DIR)
.filter((file) => file.endsWith('.json'))
.sort();
}