I've been using this method to test file-system functions as an alternative to mock-fs due to its lack of symlink support. I'd love to hear what others think and the possible dangers, pitfalls, or improvements.

var CWD = process.cwd()
var assert = require('assert')
var path = require('path')
var os = require('os')
var Promise = require('bluebird')
var fs = Promise.promisifyAll(require('fs-extra'))
// note this is a custom verison of fs-extra :(

// [[fileName, contents], expectation]
var files = [
  ['hello.js', ''],
  ['folder/file-require-local.js', 'var local = require(\'../file-require-sibling.js\')'],
  ['file-require-sibling.js', 'var local = require(\'./file-require-underscore.js\')'],
  ['file-require-underscore.js', 'var underscore = require(\'underscore\')'],
  ['file-import-underscore.js', 'import underscore from \'underscore\''],
  ['file-require-path.js', 'var path = require(\'path\')'],
  ['file-require-local.js', 'var hello = require(\'./hello.js\')'],
  ['file-import-local.js', 'import hello from \'./hello.js\''],
  ['file-require-json.js', 'var pkg = require(\'./package.json\')'],
  ['file-multi-file.js', (function () {
    var file = []
    file.push('var underscore = require(\'underscore\')')
    file.push('var path = require(\'path\')')
    file.push('var hello = require(\'./hello.js\')')
    return file.join('\n')

/* global describe, before, after, beforeEach, afterEach, it */

var ROOT_DESC = 'recursive-deps'
var TEST_DIR = path.join(os.tmpdir(), ROOT_DESC)

describe(ROOT_DESC, function () {

  before(function () {

  beforeEach(function () {
    return Promise.map(files, function (file) {
      return fs.ensureFileAsync.apply(null, file)

  afterEach(function () {

  after(function () {

  it('should have mock file system', function () {
    var dir = fs.readdirSync(TEST_DIR)
    var expected = [
    assert.equal(process.cwd().indexOf(TEST_DIR) > -1, true)
    assert.deepEqual(dir, expected)

  • \$\begingroup\$ The symlink issue is fixed now. I'm curious what is the purpose of simulating file system? You could use mocking, to represent behaviour of reading a file system - sinon library is good example. It's a bad practise to unit test on specific environment, since it might not work elsewhere. In your case test would probably fail in Windows. \$\endgroup\$ Feb 12, 2018 at 18:57


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.