Node.js測試中的Mock檔案系統詳解_node.js

來源:互聯網
上載者:User

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

總結

以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的協助,如果有疑問大家可以留言交流。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.