loadFixtures.ts 1.5 KB

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