Skip to content
Browse files

add .fake() .unfake() methods

  • Loading branch information...
1 parent cd97082 commit 70fc31b52b0878f54856f66d1d8b3b2ffdb50e1f @eldargab committed Sep 13, 2012
Showing with 54 additions and 0 deletions.
  1. +28 −0 lib/fake-fs.js
  2. +26 −0 test/fake-fs.js
View
28 lib/fake-fs.js
@@ -155,6 +155,34 @@ Fs.prototype.mkdir = function (dir, mode, cb) {
cb && cb(err, res)
}
+Fs.prototype.fake = function () {
+ this._orig = {}
+ var fs = require('fs')
+ methods.forEach(function (meth) {
+ this._orig[meth] = fs[meth]
+ fs[meth] = this[meth].bind(this)
+ }, this)
+}
+
+Fs.prototype.unfake = function () {
+ var fs = require('fs')
+ for (var key in this._orig) {
+ fs[key] = this._orig[key]
+ }
+}
+
+var methods = [
+ 'exists',
+ 'stat',
+ 'readdir',
+ 'mkdir',
+ 'readFile',
+ 'writeFile'
+].reduce(function (res, meth) {
+ res.push(meth)
+ res.push(meth + 'Sync')
+ return res
+}, [])
Fs.prototype.at = function (path) {
return new Proxy(this, path)
View
26 test/fake-fs.js
@@ -287,4 +287,30 @@ describe('Fake FS', function () {
})
})
})
+
+ describe('.fake()', function () {
+ afterEach(function () {
+ fs.unfake()
+ })
+ it('Should patch global fs with self methods', function () {
+ var global = require('fs')
+ var origStat = global.stat
+ fs.fake()
+ global.statSync.should.not.equal(origStat)
+ global.existsSync('abrakadabra').should.be.false
+ fs.dir('abrakadabra')
+ global.existsSync('abrakadabra').should.be.true
+ })
+ })
+
+ describe('.unfake()', function () {
+ it('Should restore original fs methods', function () {
+ var global = require('fs')
+ var origStat = global.stat
+ fs.fake()
+ origStat.should.not.equal(global.stat)
+ fs.unfake()
+ origStat.should.equal(global.stat)
+ })
+ })
})

0 comments on commit 70fc31b

Please sign in to comment.
Something went wrong with that request. Please try again.