Skip to content

Commit

Permalink
Exposes the root mocked filesytem if the mock is currently applied.
Browse files Browse the repository at this point in the history
* Useful for tests where you wish to make 'general' assertions over the
  whole filesystem (e.g. security testing!)
* Also addresses an issue where the bindings were having 'extraneous' keys
  left when the mock was restored. (Was unable to provide an isolated test
  for this as the 'bindings' part is internal to the mock.
  • Loading branch information
ciaranj committed Jan 27, 2017
1 parent b3d19b3 commit 839e9df
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
19 changes: 18 additions & 1 deletion lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ var realProcessProps = {
chdir: process.chdir
};


function overrideBinding(binding) {
for (var key in binding) {
if (typeof binding[key] === 'function') {
Expand All @@ -33,6 +32,12 @@ function restoreBinding() {
for (var key in realBindingProps) {
realBinding[key] = realBindingProps[key];
}
// Delete excess keys that came in when the binding was originally applied.
for (var key in realBinding) {
if( typeof realBindingProps[key] === 'undefined' ) {
delete realBinding[key];
}
}
}

function restoreProcess() {
Expand All @@ -53,6 +58,7 @@ function restoreProcess() {
var exports = module.exports = function mock(config, options) {
var system = FileSystem.create(config, options);
var binding = new Binding(system);

overrideBinding(binding);

var currentPath = process.cwd();
Expand All @@ -69,6 +75,17 @@ var exports = module.exports = function mock(config, options) {
);
};

/**
* Get hold of the mocked filesystem's 'root'
* If fs hasn't currently been replaced, this will return an empty object
*/
exports.getMockRoot = function() {
if (typeof realBinding.getSystem === 'undefined') {
return {};
} else {
return realBinding.getSystem().getRoot();
}
};

/**
* Restore the fs bindings for the real file system.
Expand Down
8 changes: 8 additions & 0 deletions test/lib/index.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,14 @@ describe('The API', function() {
mock.restore();
});

it('provides direct access to the internal filesystem object', function() {
mock();
var root=mock.getMockRoot();
assert.notDeepEqual( root, {} );
mock.restore();
assert.deepEqual( mock.getMockRoot(), {} );
});

it('creates process.cwd() and os.tmpdir() by default', function() {
mock();

Expand Down

0 comments on commit 839e9df

Please sign in to comment.