Skip to content

Commit

Permalink
feat: added testCommand callback
Browse files Browse the repository at this point in the history
  • Loading branch information
jdx committed Jan 20, 2018
1 parent 311f304 commit 016ca5e
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 6 deletions.
28 changes: 23 additions & 5 deletions src/command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,26 @@ import {expect, it, output} from '.'

export interface TestCommandOptions {
description?: string
stdout?: string
stderr?: string
stdout?: string | boolean
stderr?: string | boolean
exit?: number
root?: string
}

export const testCommand = (args: string[], opts: TestCommandOptions) => {
export type TestCommandCallback<T> = (output: T) => Promise<void> | void

export interface TestCommand {
(args: string[], opts: TestCommandOptions & {stdout: true, stderr: true}, fn: TestCommandCallback<{stdout: string, stderr: string}>): void
(args: string[], opts: TestCommandOptions & {stdout: true}, fn: TestCommandCallback<{stdout: string}>): void
(args: string[], opts: TestCommandOptions & {stderr: true}, fn: TestCommandCallback<{stderr: string}>): void
(args: string[], opts: TestCommandOptions, fn?: TestCommandCallback<{}>): void
}

export const testCommand: TestCommand = (
args: string[],
opts: TestCommandOptions,
fn?: TestCommandCallback<any>
) => {
const description = opts.description || args[0]
let test = it
if (opts.stdout) test = test.stdout
Expand All @@ -25,7 +38,12 @@ export const testCommand = (args: string[], opts: TestCommandOptions) => {
throw new Error(`Expected exit code to be ${exit} but got ${err['cli-ux'].exit}`)
}
}
if (opts.stdout) expect(output.stdout).to.equal(opts.stdout)
if (opts.stderr) expect(output.stderr).to.equal(opts.stderr)
if (typeof opts.stdout === 'string') expect(output.stdout).to.equal(opts.stdout)
if (typeof opts.stderr === 'string') expect(output.stderr).to.equal(opts.stderr)
if (!fn) return
let o: any = {}
if (opts.stdout) o.stdout = output.stdout
if (opts.stderr) o.stderr = output.stderr
await fn(o)
})
}
5 changes: 4 additions & 1 deletion test/command.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import * as path from 'path'

import {describe, testCommand} from '../src'
import {describe, expect, testCommand} from '../src'

describe('command', () => {
testCommand(['foo:bar'], {stdout: 'hello world!\n', root: path.join(__dirname, 'fixtures/multi')})
testCommand(['foo:bar', '--name=foo'], {stdout: 'hello foo!\n', root: path.join(__dirname, 'fixtures/multi')})
testCommand(['foo:bar', '--name=foo'], {stdout: true, root: path.join(__dirname, 'fixtures/multi')}, ({stdout}) => {
expect(stdout).to.equal('hello foo!\n')
})
})

0 comments on commit 016ca5e

Please sign in to comment.