I have a file foo.js that looks like this:
var exec = require('child_process').exec
...
function start(){
...
exec('open -g http://localhost:<port>'); // opens a browser window
}
// EOF
I want to test that when I call the start() function, a browser window gets opened. Ideally, I'd like to use Sinon to stub out exec (so that we don't actually open a browser window during automated tests), and assert that exec was called. I've tried many ways, none of which work. For example in 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"
});
});
});
How would I go about doing this?
Not sure if this is what you're looking for, but a quick search returned:
https://github.com/arunoda/horaa
Basically, it allows you to stub out libraries. From the examples:
Your Code
//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 :)';
}
};
Test Code (note the mocking of OS)
//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');
Hope that helps.