navy
Version:
Quick and powerful development environments using Docker and Docker Compose
83 lines (81 loc) • 3.15 kB
JavaScript
;
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _chai = require("chai");
var _sinon = _interopRequireDefault(require("sinon"));
var _events = require("events");
var _child_process = _interopRequireDefault(require("child_process"));
var _execAsync = require("../exec-async");
/* eslint-env mocha */
function createFakeChild() {
const child = new _events.EventEmitter();
child.stdout = new _events.EventEmitter();
child.stderr = new _events.EventEmitter();
return child;
}
describe('exec-async', function () {
describe('execAsync', function () {
let sandbox;
let execStub;
let fakeChild;
beforeEach(function () {
sandbox = _sinon.default.createSandbox();
fakeChild = createFakeChild();
execStub = sandbox.stub(_child_process.default, 'exec').callsFake((cmd, opts, cb) => {
process.nextTick(() => {
fakeChild.stdout.emit('data', Buffer.from('hello'));
fakeChild.stderr.emit('data', Buffer.from('warn'));
cb(null, 'hello world', '');
});
return fakeChild;
});
});
afterEach(function () {
sandbox.restore();
});
it('should resolve with stdout when the command succeeds', async function () {
const result = await (0, _execAsync.execAsync)('echo', ['hello', 'world']);
(0, _chai.expect)(result).to.equal('hello world');
(0, _chai.expect)(execStub.calledOnce).to.equal(true);
(0, _chai.expect)(execStub.firstCall.args[0]).to.equal('echo hello world');
});
it('should default args to an empty array when not provided', async function () {
const result = await (0, _execAsync.execAsync)('echo');
(0, _chai.expect)(result).to.equal('hello world');
(0, _chai.expect)(execStub.firstCall.args[0]).to.equal('echo ');
});
it('should pass opts through to child_process.exec', async function () {
const opts = {
cwd: '/tmp',
env: {
FOO: 'bar'
}
};
await (0, _execAsync.execAsync)('ls', ['-la'], null, opts);
(0, _chai.expect)(execStub.firstCall.args[1]).to.equal(opts);
});
it('should invoke the callback with the spawned child process', async function () {
const callback = _sinon.default.spy();
await (0, _execAsync.execAsync)('echo', ['hi'], callback);
(0, _chai.expect)(callback.calledOnce).to.equal(true);
(0, _chai.expect)(callback.firstCall.args[0]).to.equal(fakeChild);
});
it('should not invoke the callback when none is supplied', async function () {
await (0, _execAsync.execAsync)('echo', ['hi']);
});
it('should reject when the command fails', async function () {
execStub.restore();
const failure = new Error('boom');
execStub = sandbox.stub(_child_process.default, 'exec').callsFake((cmd, opts, cb) => {
process.nextTick(() => cb(failure));
return fakeChild;
});
let caught;
try {
await (0, _execAsync.execAsync)('false');
} catch (err) {
caught = err;
}
(0, _chai.expect)(caught).to.equal(failure);
});
});
});