forked from zowe/zowe-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fs.ts
76 lines (66 loc) · 2.35 KB
/
fs.ts
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
68
69
70
71
72
73
74
75
76
/*
* This program and the accompanying materials are made available under the terms of the
* Eclipse Public License v2.0 which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v20.html
*
* SPDX-License-Identifier: EPL-2.0
*
* Copyright Contributors to the Zowe Project.
*
*/
const path = require("path");
const fs = jest.genMockFromModule("fs") as any;
const oldReadFileSync = jest.requireActual("fs").readFileSync;
// 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 = Object.create(null);
function __setMockFiles(newMockFiles: { [key: string]: string }) {
mockFiles = Object.create(null);
for (const file in newMockFiles) {
const dir = path.dirname(file);
if (!mockFiles[dir]) {
mockFiles[dir] = {};
}
mockFiles[dir][path.basename(file)] = newMockFiles[file];
}
}
// A custom version of `readdirSync` that reads from the special mocked out
// file list set via __setMockFiles
function readdirSync(filePath: string) {
return mockFiles[filePath] || {};
}
// A custom version of `existsSync` that reads from the special mocked out
// file list set via __setMockFiles
function existsSync(filePath: string) {
const fileContents = readdirSync(path.dirname(filePath))[path.basename(filePath)];
if (typeof fileContents === "undefined") {
return false;
}
return true;
}
// A custom version of `readFileSync` that reads from the special mocked out
// file list set via __setMockFiles
function readFileSync(filePath: string, encoding?: string) {
// Don't mock if yargs is trying to load a locale json file
if (filePath.match(/node_modules.yargs/)) {
return oldReadFileSync(filePath, encoding);
}
if (!existsSync(filePath)) {
throw new Error("File not found");
}
return readdirSync(path.dirname(filePath))[path.basename(filePath)];
}
// A custom version of `lstatSync` that reads from the special mocked out
// file list set via __setMockFiles
function lstatSync(filePath: string) {
return {
isFile: () => false
};
}
fs.__setMockFiles = __setMockFiles;
fs.existsSync = existsSync;
fs.readFileSync = readFileSync;
fs.readdirSync = readdirSync;
fs.lstatSync = lstatSync;
module.exports = fs;