Home > Web Front-end > JS Tutorial > body text

Detailed explanation of Mock file system in Node.js testing

高洛峰
Release: 2016-12-06 13:21:21
Original
1566 people have browsed it

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
Copy after login

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');
  });
 });
});
Copy after login

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();
 });
Copy after login


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template