Home > Article > Web Front-end > Detailed explanation of Mock file system in Node.js testing
Mock file system related tools include:
Mock fs module tool mock-fs.
Mock require module tool mock-require.
Installation
mock-fs and mock-require are both NPM software packages, which can be installed directly through npm in the project:
npm install mock-fs mock-require --save
Mock fs module
Multiple files can be created through the mock() method Mock and take effect immediately, subsequent calls to fs will access these Mock files. Call mock.restore() to cancel the mock and restore fs.
var fs = require('fs'); var mock = require('mock-fs'); describe('fs', function() { beforeEach(function() { mock({ './CNAME': 'harttle.com', './_config.yml': 'empty' }); }); afterEach(function() { mock.restore(); }); describe('#readFileSync()', function() { it('should read all content', function() { var str = fs.readFileSync('CNAME', 'utf8'); expect(str).to.equal('harttle.com'); }); }); });
Mock require mechanism
The principle of mock-fs is to rewrite the file reading and writing function of the fs module and redirect it to the Mock file. So it doesn't work for require. In order for require to read the Mock file, the require method can only be overridden. Mock-require encapsulates this operation.
Mock through the mock method, stop Mock and restore require through mock.stopAll.
const mock = require('mock-require'); describe('parser', function() { beforeEach(function() { mock('/package.json', { "name": "sample-module", "version": "1.0.0", "view": "htmls/my-html.hbs", "router": "svr.js" }); }); afterEach(function() { mock.stopAll(); });