UNPKG

1.23 kBJavaScriptView Raw
1const realBinding = process.binding('fs');
2let storedBinding;
3
4/**
5 * Perform action, bypassing mock FS
6 * @example
7 * // This file exists on the real FS, not on the mocked FS
8 * const filePath = '/path/file.json';
9 * const data = mock.bypass(() => fs.readFileSync(filePath, 'utf-8'));
10 */
11exports = module.exports = function bypass(fn) {
12 if (typeof fn !== 'function') {
13 throw new Error(`Must provide a function to perform for mock.bypass()`);
14 }
15
16 disable();
17
18 let result;
19 try {
20 result = fn();
21 if (result && typeof result.then === 'function') {
22 return result.then(
23 r => {
24 enable();
25 return r;
26 },
27 err => {
28 enable();
29 throw err;
30 }
31 );
32 } else {
33 enable();
34 return result;
35 }
36 } catch (err) {
37 enable();
38 throw err;
39 }
40};
41
42/**
43 * Temporarily disable Mocked FS
44 */
45function disable() {
46 if (realBinding._mockedBinding) {
47 storedBinding = realBinding._mockedBinding;
48 delete realBinding._mockedBinding;
49 }
50}
51
52/**
53 * Enables Mocked FS after being disabled by disable()
54 */
55function enable() {
56 if (storedBinding) {
57 realBinding._mockedBinding = storedBinding;
58 storedBinding = undefined;
59 }
60}