Node.js测试中的Mock文件系统详解
Node.js测试中的Mock文件系统详解
发布时间:2016-12-30 来源:查字典编辑
摘要:Mock文件系统相关的工具包括:Mockfs模块的工具mock-fs。Mockrequire模块的工具mock-require。安装mock...

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

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流。

推荐文章
猜你喜欢
附近的人在看
推荐阅读
拓展阅读
相关阅读
网友关注
最新Javascript教程学习
热门Javascript教程学习
编程开发子分类