loadFixtures.ts 1.9 KB

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