tschaub / mock-fs

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

Mock child process #298

Closed johnsonsamuel closed 4 years ago

johnsonsamuel commented 4 years ago

What is this about?

Mock node's child process exec or spawn ?

Just wanted to check if there is a possibility of mocking node process.

__installPackage.js__

const {promisify} = require('util');
const exec = (require('child_process').exec);

const listFolderContent = async (root) => {
    const options = {
        cwd: root
    };

    await exec('ls -l', options, (err, data) => {
        if(err) console.log('error', err);
    });
};
_installPackage.test.js_

const mock = require('mock-fs');
const {listFolderContent} = require('./listFolderContent');

describe('listFolderContent', async assert => {
    const root = 'my-app';

    mock({
        'my-app': {
            'test.txt': 'samuel'
        }

    });

   await listFolderContent(root);    

   mock.restore();
});

My question is, will the exec work and list the content from the mock fs?

which is test.txt?

3cp commented 4 years ago

The answer is no. Mockfs cannot do it. First, exec or spawn creates new OS process which is isolated from current nodejs process. Even if you do exec("node some.js") to create another nodejs process, the new process is not affected by mockfs on current process.

Furthermore, ls uses libc to access file system, it's irrelevant to mockfs which only mocks nodejs's fs module.

johnsonsamuel commented 4 years ago

Thank you @3cp for your detailed explanation. I was able to mock exec using sinon. I was able to use mock-fs as well.