Skip to content

Commit

Permalink
Merge pull request #3 from dead-horse/support-spawn
Browse files Browse the repository at this point in the history
Support mock `child_process.spawn`
  • Loading branch information
fengmk2 committed May 5, 2013
2 parents 38ac8f7 + b90710a commit 1f8dc9d
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 2 deletions.
22 changes: 21 additions & 1 deletion lib/mm.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ var EventEmitter = require('events').EventEmitter;
var muk = require('muk');
var http = require('http');
var https = require('https');

var cp = require('child_process');
var EventEmitter = require('events').EventEmitter;

exports = module.exports = function mock(obj, key, method) {
return muk.apply(null, arguments);
Expand Down Expand Up @@ -305,6 +306,25 @@ function _requestError(mod, url, reqError, resError, delay) {
return this;
}

/**
* mock child_process spawn
* @param {Integer} code exit code
* @param {String} stdout
* @param {String} stderr
* @param {Integer} timeout stdout/stderr/close event emit timeout
*/
exports.spawn = function (code, stdout, stderr, timeout) {
var evt = new EventEmitter();
muk(cp, 'spawn', function () {
return evt;
});
setTimeout(function () {
stdout && evt.emit('stdout', stdout);
stderr && evt.emit('stderr', stderr);
evt.emit('close', code);
}, timeout);
};

/**
* remove all mock effects.
*/
Expand Down
28 changes: 27 additions & 1 deletion test/mm.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,10 @@ var fs = require('fs');
var should = require('should');
var http = require('http');
var https = require('https');
var child_process = require('child_process');
var pedding = require('pedding');
var foo = require('./foo');


describe('mm.test.js', function () {

var port = null;
Expand Down Expand Up @@ -524,6 +524,32 @@ describe('mm.test.js', function () {

});

describe('spawn', function () {
it('should mm.spawn mock spawn', function (done) {
mm.spawn(1, 'stdout', 'stderr', 100);
var ls = child_process.spawn('ls', ['-a']);
var done = pedding(4, done);
ls.on('stdout', function (data) {
data.should.equal('stdout');
done();
});
ls.on('stderr', function (data) {
data.should.equal('stderr');
done();
});
ls.on('close', function (code) {
code.should.equal(1);
done();
});
mm.restore();
var ls = child_process.spawn('ls', ['-a']);
ls.on('close', function (code) {
code.should.equal(0);
done();
});
});
});

describe('mm()', function () {
it('should mm() just like muk()', function (done) {
mm(fs, 'readFile', function (filename, callback) {
Expand Down

0 comments on commit 1f8dc9d

Please sign in to comment.