在Node.js测试中Mock文件系统
在Node.js测试中,常常会需要构造某种项目目录。 为每个测试用例添加相应的目录结构既费时又难以维护。 这时Mock文件系统便是最佳选择,相关的工具包括:
- Mock
fs模块的工具mock-fs。 - Mock
require模块的工具mock-require。
安装
mock-fs和 mock-require
都是NPM软件包,在项目中可通过npm直接安装:
npm install mock-fs mock-require --save
Mock fs 模块
通过mock()方法可以创建多个文件的Mock并立即生效,
此后对fs的调用都会访问这些Mock文件。
调用mock.restore()可取消Mock并恢复fs。
var fs = require('fs');
var mock = require('mock-fs');
describe('fs', function() {
beforeEach(function() {
mock({
'./CNAME': 'harttle.land',
'./_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.land');
});
});
});
Mock require 机制
mock-fs的原理是重写fs模块的文件读写功能,重定向到Mock文件。
所以对require并不起作用。
为了让require读取Mock文件,只能重写require方法。
mock-require便是封装了该操作。
通过mock方法进行Mock,通过mock.stopAll()停止Mock并恢复require。
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();
});
});
本文采用 知识共享署名 4.0 国际许可协议(CC-BY 4.0)进行许可,转载注明来源即可: https://harttle.land/2016/08/01/javascript-mock-fs.html。如有疏漏、谬误、侵权请通过评论或 邮件 指出。