模拟 Node.js 中的嵌套模块
Mocking a nested module in Node.js?
我有这些文件:
文件1.js
var mod1 = require('mod1');
mod1.someFunction()
...
文件2.js
var File1 = require('./File1');
现在,在为 File2 编写单元测试时,是否可以模拟mod1
,这样我就不会调用mod1.someFunction()
?
我通常使用mockery
模块,如下所示:
库/文件1.js
var mod1 = require('./mod1');
mod1.someFunction();
库/文件2.js
var file1 = require('./file1');
lib/mod1.js
module.exports.someFunction = function() {
console.log('hello from mod1');
};
测试/文件1.js
/* globals describe, before, beforeEach, after, afterEach, it */
'use strict';
//var chai = require('chai');
//var assert = chai.assert;
//var expect = chai.expect;
//var should = chai.should();
var mockery = require('mockery');
describe('config-dir-all', function () {
before('before', function () {
// Mocking the mod1 module
var mod1Mock = {
someFunction: function() {
console.log('hello from mocked function');
}
};
// replace the module with mock for any `require`
mockery.registerMock('mod1', mod1Mock);
// set additional parameters
mockery.enable({
useCleanCache: true,
//warnOnReplace: false,
warnOnUnregistered: false
});
});
beforeEach('before', function () {
});
afterEach('after', function () {
});
after('after', function () {
// Cleanup mockery
after(function() {
mockery.disable();
mockery.deregisterMock('mod1');
});
});
it('should throw if directory does not exists', function () {
// Now File2 will use mock object instead of real mod1 module
var file2 = require('../lib/file2');
});
});
正如之前建议的那样,sinon
模块非常方便构建模拟。
当然。 有 2 个非常流行的节点.js库专门用于模拟需求。
https://github.com/jhnns/rewire
https://github.com/mfncooper/mockery
它们都有不同的API,并且重新布线有一些奇怪的警告。
相关文章:
- 用嵌套函数和默认函数定义函数
- 如何在ReactJS JSX中执行嵌套的if-else语句
- 可以简化嵌套的延迟Q Promises解析吗
- 用于搜索的聚合物嵌套绑定
- 在嵌套组件中使用 react 组件时模块中断
- 从节点模块内部返回嵌套函数
- 模拟 Node.js 中的嵌套模块
- AngularJS中的嵌套模块
- 如何嵌套 React 组件/模块以分离 UI
- 避免在ES6 JavaScript web项目中进行深度嵌套模块导入
- 如何需要深度嵌套的NodeJS模块
- Javascript模块模式:在嵌套函数中调用函数
- Javascript模块扩展嵌套对象
- 如何在嵌套的IIFE模块中引用父JavaScript函数
- 如何从嵌套模块导入
- AngularJS中的嵌套模块
- 如何在模块化设计模式中嵌套函数
- 将嵌套模块与require.js优化器结合起来
- “this”在嵌套异步模块函数中如何正常表现
- 引用嵌套的TypeScript模块