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(); });總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流。
 
  | 
新聞熱點
疑難解答