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.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();
});
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号