balena-cli/tests/helpers.ts
Lucian 4d389bb6cc Implement full command testing, beginning with "balena version"
This also modifies the core CLI to be fed command programatically, which
is useful for being able to do thing like mock endpoints with tools like
"nock", and provide an easier debugging experience.
The tests utilise a "runCommand" helper that intercepts and captures
stdout/stderr writes and returns them once the command has finished
running. At this point the test implementation can parse the
stdout/stderr logs and assess nock interceptions to determine if the
command ran correctly.
This change also homogenises debug messages to start with `[debug]`,
however this is not strictly enforced by linting rules.

Change-type: minor
Signed-off-by: Lucian <lucian.buzzo@gmail.com>
2019-08-12 14:50:41 +01:00

49 lines
982 B
TypeScript

import * as path from 'path';
import * as balenaCLI from '../build/app';
export const runCommand = async (cmd: string) => {
const preArgs = [process.argv[0], path.join(process.cwd(), 'bin', 'balena')];
const oldStdOut = process.stdout.write;
const oldStdErr = process.stderr.write;
const err: string[] = [];
const out: string[] = [];
// @ts-ignore
process.stdout.write = (log: string) => {
// Skip over debug messages
if (!log.startsWith('[debug]')) {
out.push(log);
}
oldStdOut(log);
};
// @ts-ignore
process.stderr.write = (log: string) => {
// Skip over debug messages
if (!log.startsWith('[debug]')) {
err.push(log);
}
oldStdErr(log);
};
try {
await balenaCLI.run(preArgs.concat(cmd.split(' ')), {
noFlush: true,
});
process.stdout.write = oldStdOut;
process.stderr.write = oldStdErr;
return {
err,
out,
};
} catch (err) {
process.stdout.write = oldStdOut;
process.stderr.write = oldStdErr;
throw err;
}
};