-
Notifications
You must be signed in to change notification settings - Fork 85
/
bypass.js
executable file
·59 lines (53 loc) · 1.16 KB
/
bypass.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
const realBinding = process.binding('fs');
let storedBinding;
/**
* Perform action, bypassing mock FS
* @example
* // This file exists on the real FS, not on the mocked FS
* const filePath = '/path/file.json';
* const data = mock.bypass(() => fs.readFileSync(filePath, 'utf-8'));
*/
exports = module.exports = function bypass(fn) {
if (typeof fn !== 'function') {
throw new Error(`Must provide a function to perform for mock.bypass()`);
}
disable();
let result;
try {
result = fn();
} finally {
if (result && typeof result.then === 'function') {
result.then(
r => {
enable();
return r;
},
err => {
enable();
throw err;
}
);
} else {
enable();
}
}
return result;
};
/**
* Temporarily disable Mocked FS
*/
function disable() {
if (realBinding._mockedBinding) {
storedBinding = realBinding._mockedBinding;
delete realBinding._mockedBinding;
}
}
/**
* Enables Mocked FS after being disabled by disable()
*/
function enable() {
if (storedBinding) {
realBinding._mockedBinding = storedBinding;
storedBinding = undefined;
}
}