UNPKG

2.22 kBJavaScriptView Raw
1var realFs = require('fs');
2var path = require('path');
3
4var rewire = require('rewire');
5
6var Binding = require('./binding');
7var FileSystem = require('./filesystem');
8
9var minor = process.versions.node.split('.').slice(0, 2).join('.');
10var versions = {
11 '0.8': 'fs-0.8.26.js',
12 '0.9': 'fs-0.9.12.js',
13 '0.10': 'fs-0.10.24.js',
14 '0.11': 'fs-0.11.10.js'
15};
16
17var fsName = versions[minor];
18if (!fsName) {
19 throw new Error('Unsupported Node version: ' + process.versions.node);
20}
21
22
23/**
24 * Hijack the real fs module immediately so the binding can be swapped at will.
25 * This works as expected in cases where mock-fs is required before any other
26 * module that wraps fs exports.
27 */
28var mockFs = rewire(path.join(__dirname, '..', 'node', fsName));
29var originalBinding = mockFs.__get__('binding');
30var originalStats = mockFs.Stats;
31for (var name in mockFs) {
32 realFs[name] = mockFs[name];
33}
34
35function setBinding(binding, Stats) {
36 mockFs.__set__('binding', binding);
37 mockFs.Stats = realFs.Stats = Stats;
38}
39
40
41/**
42 * Swap out the fs bindings for a mock file system.
43 * @param {Object} config Mock file system configuration.
44 */
45var exports = module.exports = function mock(config) {
46 var system = FileSystem.create(config);
47 var binding = new Binding(system);
48 setBinding(binding, binding.Stats);
49};
50
51
52/**
53 * Restore the fs bindings for the real file system.
54 */
55exports.restore = function() {
56 setBinding(originalBinding, originalStats);
57};
58
59
60/**
61 * Create a mock fs module based on the given file system configuration.
62 * @param {Object} config File system configuration.
63 * @return {Object} A fs module with a mock file system.
64 */
65exports.fs = function(config) {
66 var system = FileSystem.create(config);
67 var binding = new Binding(system);
68
69 // inject the mock binding
70 var mockFs = rewire(path.join(__dirname, '..', 'node', fsName));
71 mockFs.__set__('binding', binding);
72
73 // overwrite fs.Stats from original binding
74 mockFs.Stats = binding.Stats;
75
76 return mockFs;
77};
78
79
80/**
81 * Create a file factory.
82 */
83exports.file = FileSystem.file;
84
85
86/**
87 * Create a directory factory.
88 */
89exports.directory = FileSystem.directory;
90
91
92/**
93 * Create a symbolic link factory.
94 */
95exports.symlink = FileSystem.symlink;