loadFixtures.ts 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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 fixtures. Supports js and 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 fixturesPairs = files.map(file => {
  19. const filePath = path.join(from, file);
  20. if (/[jt]sx?$/.test(file)) {
  21. const module = require(filePath);
  22. if (Object.keys(module).includes('default')) {
  23. throw new Error('Javascript fixtures cannot use default export');
  24. }
  25. return [file, module] as const;
  26. }
  27. if (/json$/.test(file)) {
  28. return [file, JSON.parse(fs.readFileSync(filePath).toString())] as const;
  29. }
  30. throw new Error(`Invalid fixture type found: ${file}`);
  31. });
  32. const fixtures = Object.fromEntries(fixturesPairs);
  33. if (opts.flatten) {
  34. return Object.values(fixtures).reduce((acc, val) => ({...acc, ...val}), {});
  35. }
  36. return fixtures;
  37. }