tschaub / mock-fs

Configurable mock for the fs module
https://npmjs.org/package/mock-fs
Other
911 stars 86 forks source link

mkdirSync is not using mocked FS #297

Closed cloakedninjas closed 4 years ago

cloakedninjas commented 4 years ago

Given a simple example

// example.js
const fs = require('fs');

module.exports = {
  doSomething: function () {
    fs.mkdirSync('assets/new-dir');
  }
}

And the following test:

// example.test.ts
const mockFS = require('mock-fs');
const test = require('./example');

describe('test', () => {
    beforeEach(() => {
        mockFS({
            'assets': {}
        });
    });

    afterEach(() => {
        mockFS.restore();
    });

    test.doSomething();
})

Produces the error: ENOENT: no such file or directory, mkdir 'assets/new-dir' - which sounds like FS is actually trying to make that directory, in fact it is, because if I use {recursive: true} I get an actual folder created on my machine

FYI - I'm using Node v12.16.1

3cp commented 4 years ago

Because your test code is wrong, your doSomething happened before beforeEach executes.

Try

describe('test', () => {
    beforeEach(() => {
        mockFS({
            'assets': {}
        });
    });

    afterEach(() => {
        mockFS.restore();
    });

    it(test', () => {
      test.doSomething();
    });
});