Mock file system-related tools include:
Mock fs
the tools of the module mock-fs
.
Mock require
the tools of the module mock-require
.
Installation
mock-fs
And 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-fs
The 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.