nodejs,mock,nodejs,mock框架,nodejs,单元测试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(); }); 总结 以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流。 nodejs,mock,nodejs,mock框架,nodejs,单元测试
|