Mock file system in Node.js test _node.js

Source: Internet
Author: User

Mock file system-related tools include:

Mock fsthe tools of the module mock-fs .

Mock requirethe tools of the module mock-require .

Installation

mock-fsAnd mock-require are NPM packages, which can be installed directly through NPM in the project:

NPM Install Mock-fs Mock-require--save

Mock FS Module

A mock() method can create a mock of multiple files and take effect immediately, and subsequent calls to FS will access these mock files. Call mock.restore() to cancel the mock and restore 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 mechanism

mock-fsThe principle is to rewrite the FS module's file read and write capabilities and redirect to mock files. So it require doesn't work. In order require for Mock the file to be read, only methods can be overridden require . is to mock-require encapsulate the operation.

By mock means of a method Mock , by mock.stopAll stopping Mock and resuming require .

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

Summarize

The above is the entire content of this article, I hope the content of this article for everyone's study or work can bring certain help, if you have questions you can message exchange.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.