fs-extra.ts 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. import path from 'path';
  2. const fs: {
  3. __createMockFiles: typeof createMockFiles;
  4. readFileSync: typeof readFileSync;
  5. existsSync: typeof existsSync;
  6. writeFileSync: typeof writeFileSync;
  7. mkdirSync: typeof mkdirSync;
  8. rmSync: typeof rmSync;
  9. readdirSync: typeof readdirSync;
  10. copyFileSync: typeof copyFileSync;
  11. copySync: typeof copyFileSync;
  12. } = jest.genMockFromModule('fs-extra');
  13. let mockFiles = Object.create(null);
  14. const createMockFiles = (newMockFiles: Record<string, string>) => {
  15. mockFiles = Object.create(null);
  16. // Create folder tree
  17. for (const file in newMockFiles) {
  18. const dir = path.dirname(file);
  19. if (!mockFiles[dir]) {
  20. mockFiles[dir] = [];
  21. }
  22. mockFiles[dir].push(path.basename(file));
  23. mockFiles[file] = newMockFiles[file];
  24. }
  25. };
  26. const readFileSync = (p: string) => {
  27. return mockFiles[p];
  28. };
  29. const existsSync = (p: string) => {
  30. return mockFiles[p] !== undefined;
  31. };
  32. const writeFileSync = (p: string, data: any) => {
  33. mockFiles[p] = data;
  34. };
  35. const mkdirSync = (p: string) => {
  36. mockFiles[p] = Object.create(null);
  37. };
  38. const rmSync = (p: string, options: { recursive: boolean }) => {
  39. if (options.recursive) {
  40. delete mockFiles[p];
  41. } else {
  42. delete mockFiles[p][Object.keys(mockFiles[p])[0]];
  43. }
  44. };
  45. const readdirSync = (p: string) => {
  46. const files: string[] = [];
  47. const depth = p.split('/').length;
  48. Object.keys(mockFiles).forEach((file) => {
  49. if (file.startsWith(p)) {
  50. const fileDepth = file.split('/').length;
  51. if (fileDepth === depth + 1) {
  52. files.push(file.split('/').pop() || '');
  53. }
  54. }
  55. });
  56. return files;
  57. };
  58. const copyFileSync = (source: string, destination: string) => {
  59. mockFiles[destination] = mockFiles[source];
  60. };
  61. const copySync = (source: string, destination: string) => {
  62. mockFiles[destination] = mockFiles[source];
  63. if (mockFiles[source] instanceof Array) {
  64. mockFiles[source].forEach((file: string) => {
  65. mockFiles[destination + '/' + file] = mockFiles[source + '/' + file];
  66. });
  67. }
  68. };
  69. fs.readdirSync = readdirSync;
  70. fs.existsSync = existsSync;
  71. fs.readFileSync = readFileSync;
  72. fs.writeFileSync = writeFileSync;
  73. fs.mkdirSync = mkdirSync;
  74. fs.rmSync = rmSync;
  75. fs.copyFileSync = copyFileSync;
  76. fs.copySync = copySync;
  77. fs.__createMockFiles = createMockFiles;
  78. module.exports = fs;