loadFixtures.ts 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /* global __dirname */
  2. import fs from 'node:fs';
  3. import path from 'node:path';
  4. const FIXTURES_ROOT = path.join(__dirname, '../../../fixtures');
  5. type Options = {
  6. /**
  7. * Flatten all fixtures to together into a single object
  8. */
  9. flatten?: boolean;
  10. };
  11. /**
  12. * Loads a directory of JSON fixtures.
  13. */
  14. export function loadFixtures(dir: string, opts: Options = {}) {
  15. const from = path.join(FIXTURES_ROOT, dir);
  16. const files = fs.readdirSync(from);
  17. const fixtures: Record<string, any> = {};
  18. for (const file of files) {
  19. const filePath = path.join(from, file);
  20. if (/json$/.test(file)) {
  21. fixtures[file] = JSON.parse(fs.readFileSync(filePath).toString());
  22. continue;
  23. }
  24. throw new Error(`Invalid fixture type found: ${file}`);
  25. }
  26. if (opts.flatten) {
  27. const flattenedFixtures: Record<string, any> = {};
  28. for (const moduleKey in fixtures) {
  29. for (const moduleExport in fixtures[moduleKey]) {
  30. // Check if our flattenedFixtures already contains a key with the same export.
  31. // If it does, we want to throw and make sure that we dont silently override the fixtures.
  32. if (flattenedFixtures?.[moduleKey]?.[moduleExport]) {
  33. throw new Error(
  34. `Flatten will override ${flattenedFixtures[moduleKey]} with ${fixtures[moduleKey][moduleExport]}`
  35. );
  36. }
  37. flattenedFixtures[moduleExport] = fixtures[moduleKey][moduleExport];
  38. }
  39. }
  40. return flattenedFixtures;
  41. }
  42. return fixtures;
  43. }