我有一个文件foo.js
,如下所示:
var exec = require('child_process').exec
...
function start(){
...
exec('open -g http://localhost:<port>'); // opens a browser window
}
// EOF
我想测试一下,当我调用start()
函数时,浏览器窗口会被打开。理想情况下,我想使用Sinon来存根exec
(这样我们就不会在自动化测试中实际打开浏览器窗口),并断言exec
是调用。我尝试过很多方法,但都没有。例如,在foo_test.js
:
var subject = require('../lib/foo');
describe('foo', function(){
describe('start', function(){
it('opens a browser page to the listening address', function(){
var stub = sinon.stub(subject, 'exec', function(){
console.log('stubbed exec called');
}); // fails with "TypeError: Attempted to wrap undefined property exec as function"
});
});
});
我将如何做到这一点?
答案 0 :(得分:0)
不确定这是否是您要找的,但是返回了快速搜索:
https://github.com/arunoda/horaa
基本上,它允许你存根库。从示例:
您的代码
//stored in abc.js
exports.welcome = function() {
var os = require('os');
if(os.type() == 'linux') {
return 'this is a linux box';
} else {
return 'meka nam linux nemei :)';
}
};
测试代码(注意操作系统的模拟)
//stored in test.js
var horaa = require('horaa');
var lib = require('./abc'); // your code
var assert = require('assert');
//do the hijacking
var osHoraa = horaa('os');
osHoraa.hijack('type', function() {
return 'linux';
});
assert.equal(lib.welcome(), 'this is a linux box');
//restore the method
osHoraa.restore('type');
希望有所帮助。