Skip to content

Commit

Permalink
Fix CLI arg parsing test failures by resetting Yargs
Browse files Browse the repository at this point in the history
The Yargs library (https://yargs.js.org/) has been giving me a lot of trouble due to unclear docs and “magic” behavior such as wrapping errors my code throws and keeping global state that needs to be reset. Next time I add arg parsing to a program, I won’t use Yargs.
  • Loading branch information
roryokane committed Apr 18, 2020
1 parent bfa3ee4 commit 959b841
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 7 deletions.
14 changes: 7 additions & 7 deletions cli_arg_parsing.test.ts
Expand Up @@ -4,20 +4,20 @@ function parseArgvInTestMode(argv: Array<string>) {
return parseArgv(argv, { outputAndExitOnError: false })
}

test.skip("rejects too many file arguments", () => {
test("rejects too many file arguments", () => {
expect(() => {
parseArgv(["file1.xsc", "file2.xsc"], { outputAndExitOnError: false })
parseArgvInTestMode(["file1.xsc", "file2.xsc"])
}).toThrow()
})

test.skip("rejects unknown format", () => {
test("rejects unknown format", () => {
expect(() => {
parseArgv(["--format", "transcribe_version_999"], { outputAndExitOnError: false })
parseArgvInTestMode(["--format", "transcribe_version_999"])
}).toThrow()
})

test("accepts one file", () => {
expect(parseArgv(["some file with spaces.xsc"], { outputAndExitOnError: false })).toEqual({
expect(parseArgvInTestMode(["some file with spaces.xsc"])).toEqual({
inputSource: {
filePath: "some file with spaces.xsc",
type: "file",
Expand All @@ -27,14 +27,14 @@ test("accepts one file", () => {
})

test("interprets no files as stdin", () => {
expect(parseArgv([], { outputAndExitOnError: false })).toEqual({
expect(parseArgvInTestMode([])).toEqual({
inputSource: { type: "stdin" },
outputFormat: "generic",
})
})

test("interprets - as stdin", () => {
expect(parseArgv(["-"], { outputAndExitOnError: false })).toEqual({
expect(parseArgvInTestMode(["-"])).toEqual({
inputSource: { type: "stdin" },
outputFormat: "generic",
})
Expand Down
4 changes: 4 additions & 0 deletions cli_arg_parsing.ts
Expand Up @@ -15,6 +15,10 @@ export function parseArgv(
argv: Array<string>,
options: { outputAndExitOnError: boolean } = { outputAndExitOnError: true }
) {
// yargs.reset() is needed to make multiple `yargs` calls in a single program, e.g. in tests, work independently.
// That’s why I’m calling it even though the Yargs docs say it’s deprecated. The docs don’t say what to use instead.
yargs.reset()

const yargsParser = yargs
.usage("$0 [option] [file]")
.example("$0 myTranscribeFile.xsc", "reading input with a file argument")
Expand Down

0 comments on commit 959b841

Please sign in to comment.