如何在Node.js中模拟一个glob调用

我正在使用Mocha,Chai和Sinon JS为我的Node.js应用程序编写unit testing。

这是我想testing的模块:

var glob = require('glob'); var pluginInstaller = require('./pluginInstaller'); module.exports = function(app, callback) { 'use strict'; if (!app) { return callback(new Error('App is not defined')); } glob('./plugins/**/plugin.js', function(err, files) { if (err) { return callback(err); } pluginInstaller(files, callback, app); }); }; 

我有一个testing的情况下,当没有应用程序使用.to.throw(Error)

但是我不知道如何模拟glob调用。 特别是我想告诉我的testing方法,glob-call返回什么,然后检查,如果pluginInstaller被调用,使用sinon.spy

这是我迄今为止的testing:

 var expect = require('chai').expect, pluginLoader = require('../lib/pluginLoader'); describe('loading the plugins', function() { 'use strict'; it ('returns an error with no app', function() { expect(function() { pluginLoader(null); }).to.throw(Error); }); }); 

首先,你需要一个工具,让你钩入require函数并改变它返回的内容。 我build议proxyquire ,那么你可以做一些像:

然后你需要一个存根,实际上产生的callback给glob函数。 幸好, sinon已经得到了:

 const globMock = sinon.stub().yields(); 

在一起,你可以这样做:

  pluginLoader = proxyquire('../lib/pluginLoader', { 'glob' : globMock }); 

现在,当你调用pluginLoader并且达到glob -Function时,Sinon将调用参数中的第一个callback函数。 如果你真的需要在callback中提供一些参数,你可以把它们作为数组传递给yields函数,比如yields([arg1, arg2])