Mock文件系统相关的工具包括:
Mock fs 模块的工具
mock-fs 。
Mock require 模块的工具
mock-require 。安装
mock-fs和
mock-require 都是NPM软件包,在项目中可通过npm直接安装:
npm install mock-fs mock-require --saveMock 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.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 机制
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();
});
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流。









