-
Notifications
You must be signed in to change notification settings - Fork 319
/
fs-extra.js
67 lines (56 loc) · 1.87 KB
/
fs-extra.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import path from 'path';
import R from 'ramda';
const fs = jest.genMockFromModule('fs-extra');
// This is a custom function that our tests can use during setup to specify
// what the files on the "mock" filesystem should look like when any of the
// `fs` APIs are used.
let mockFiles = {};
let mockFilesMeta = {};
fs.setMock = (mockFileSystem, mockFilesSystemMeta) => {
mockFiles = mockFileSystem;
mockFilesMeta = mockFilesSystemMeta;
};
fs.readFileSync = filePath => mockFiles[filePath];
fs.readFile = async filePath => fs.readFileSync(filePath);
// A custom version of `readdirSync` that reads from the special mocked out
// file list set via setMock
fs.readdirSync = (directoryPath) => {
const pathArr = directoryPath.split(path.sep);
return Object.keys(R.path(pathArr, mockFiles)) || [];
};
// A custom version of `readdir` that reads from the special mocked out
// file list set via setMock
fs.readdir = async directoryPath => fs.readdirSync(directoryPath);
// A custom version of `readJson` that reads from the special mocked out
// file list set via setMock
/**
* A custom version of `readJson` that reads from the mocked out file system.
* Reads json from string, error otherwise.
*/
fs.readJson = async (directoryPath) => {
const pathArr = directoryPath.split(path.sep);
try {
return JSON.parse(R.path(pathArr, mockFiles));
} catch (error) {
return Promise.reject(error);
}
};
/**
* A custom version of `readJsonSync` that reads from the mocked out file system.
* Reads json from string, error otherwise.
*/
fs.readJsonSync = (directoryPath) => {
const pathArr = directoryPath.split(path.sep);
return JSON.parse(R.path(pathArr, mockFiles));
};
/**
* Mocks and fakes meta data for the file
*/
fs.stat = async (filePath) => {
const meta = mockFilesMeta[filePath];
if (!meta) {
throw new Error('No such file');
}
return meta;
};
module.exports = fs;