Skip to content

Instantly share code, notes, and snippets.

@heyimalex
Created September 21, 2016 16:15

Revisions

  1. heyimalex created this gist Sep 21, 2016.
    24 changes: 24 additions & 0 deletions example.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,24 @@
    // __tests__/example.js
    jest.mock('fs');

    it('should serve as a nice example', () => {

    const fs = require('fs')

    // fs can be set up at any point by calling __configureFs.
    fs.__configureFs({
    '/test': {
    'a.foo': '----',

    // mock-fs' other exports are also available on the fs object.
    'b.bar': fs.__mockFile({
    content: 'file content here',
    ctime: new Date(1),
    mtime: new Date(1)
    }),
    })

    const results = fs.readdirSync('/test')
    expect(results.length).toBe(2)
    expect(results).toEqual(['a.foo', 'b.bar'])
    })
    27 changes: 27 additions & 0 deletions fs.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,27 @@
    // __mocks__/fs.js
    const mockfs = require('mock-fs');

    const container = {
    __internalFs: null,
    __configureFs: (conf) => {
    container.__internalFs = mockfs.fs(conf);
    },
    __mockFile: mockfs.file,
    __mockDirectory: mockfs.directory,
    __mockSymlink: mockfs.symlink,
    }

    const proxyfs = new Proxy(container, {
    get: function (target, property, receiver) {
    if (target.hasOwnProperty(property)) {
    return target[property];
    } else {
    if (target.__internalFs === null) {
    target.__internalFs = mockfs.fs();
    }
    return target.__internalFs[property];
    }
    }
    })

    module.exports = proxyfs;
    7 changes: 7 additions & 0 deletions jestsetup.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,7 @@
    // mock-fs hooks the native fs on first require, so unfortunately just using
    // the __mocks__ file isn't enough; jest will mock fs itself and stuff gets
    // complicated. I'm actually not completely sure _what_ happens, but the end
    // result is that you need to require mock fs before anything else or it
    // doesn't work.

    require('mock-fs')
    12 changes: 12 additions & 0 deletions package.json
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,12 @@
    {
    "devDependencies": {
    "jest": "^15.1.1",
    "mock-fs": "^3.11.0",
    },
    "scripts": {
    "test": "jest"
    },
    "jest": {
    "setupFiles": ["<rootDir>/jestsetup.js"]
    }
    }