sourcecred/src/cli/testUtil.test.js
William Chargin 4c433d417e
cli: add command infrastructure and test utils (#740)
Summary:
This commit introduces the notion of a `Command`, which is simply a
function that takes command-line arguments and interacts with the real
world. This infrastructure will enable us to write a well-tested CLI.

The `Command` interface is asynchronous because commands like `load`
need to block on promise resolution (for loading GitHub and Git data).
This is annoying for testing, but does not actually appear to be a
problem in practice.

Test Plan:
Unit tests added. See later commits for real-world usage.

wchargin-branch: cli-command-infrastructure
2018-09-02 15:48:47 -07:00

70 lines
1.7 KiB
JavaScript

// @flow
import type {Command} from "./command";
import {run} from "./testUtil";
describe("cli/testUtil", () => {
const testCommand: Command = async (args, std) => {
switch (args[0]) {
case "good":
std.out("all");
std.out("is");
std.out("well");
return 0;
case "bad":
std.out("something's");
std.err("not");
std.out("right");
return 1;
case "throw":
std.out("???");
std.err("what is going on");
throw new Error(args[0]);
case "reject":
std.out("!!!");
std.err("something is going on!");
return Promise.reject(args[0]);
default:
console.error("Actually shouldn't happen");
return 2;
}
};
describe("run", () => {
it("captures stdout with a successful command", async () => {
expect(await run(testCommand, ["good"])).toEqual({
exitCode: 0,
stdout: ["all", "is", "well"],
stderr: [],
});
});
it("captures stderr with a failed command", async () => {
expect(await run(testCommand, ["bad"])).toEqual({
exitCode: 1,
stdout: ["something's", "right"],
stderr: ["not"],
});
});
it("handles exceptions", async () => {
expect(await run(testCommand, ["throw"])).toEqual({
exitCode: 1,
stdout: ["???"],
stderr: [
"what is going on",
expect.stringMatching(/^Error: throw\n *at testCommand/),
],
});
});
it("handles exceptions", async () => {
expect(await run(testCommand, ["reject"])).toEqual({
exitCode: 1,
stdout: ["!!!"],
stderr: ["something is going on!", '"reject"'],
});
});
});
});