我正在使用Mocha,Chai和Sinon JS为我的Node.js应用程序编写单元测试。
这是我想要测试的模块:
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);
});
};
我有一个案例测试,当没有使用.to.throw(Error)
的应用程序时。
但我不知道如何嘲笑全球电话。特别是我想告诉我的测试方法,glob-call 返回什么,然后使用 sinon.spy
检查是否已调用插件安装程序。
这是我到目前为止的测试:
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
函数并改变它返回的内容。我建议代理查询,然后你可以做这样的事情:
然后你需要一个存根,它实际上产生给 glob 函数的回调。幸运的是,sinon
已经明白了:
const globMock = sinon.stub().yields();
在一起,您可以像这样做到这一点:
pluginLoader = proxyquire('../lib/pluginLoader', {
'glob' : globMock
});
现在,当你调用插件加载器并且它到达glob
-Function时,Sinon 将调用参数中的第一个回调。如果你真的需要在回调中提供一些参数,你可以将它们作为数组传递给yields
函数,比如yields([arg1, arg2])
。