Skip to content

Instantly share code, notes, and snippets.

@pkoch

pkoch/test.ts

Created Jan 1, 2020
Embed
What would you like to do?
import R from 'ramda'
import { mockProcessExit, mockProcessStdout, mockProcessStderr, mockConsoleLog } from 'jest-mock-process'
import { main } from './main'
describe('main', () => {
const lineize = ({result, stdout, stderr, log, exit}: {
result: any,
stdout: string[][]
stderr: string[][],
log: string[][],
exit: number[][],
}): any => {
const lineize = R.map(R.head)
const flatLineize = R.pipe(
lineize,
R.map(s => s.trim().split('\n')),
R.reduce((a, v) => a.concat(v), []),
)
return {
result,
stdout: flatLineize(stdout),
stderr: flatLineize(stderr),
log: flatLineize(log),
exit: lineize(exit),
}
}
const mockedRun = async (f: (() => void)) => {
const mockExit = mockProcessExit();
const mockStdout = mockProcessStdout();
const mockStderr = mockProcessStderr();
const mockLog = mockConsoleLog();
const result = await f()
const out = {
result,
stdout: mockStdout.mock.calls,
stderr: mockStderr.mock.calls,
log: mockLog.mock.calls,
exit: mockExit.mock.calls,
}
;[
mockExit,
mockStdout,
mockStderr,
mockLog,
].forEach(o => o.mockRestore())
return out
}
const run = async (...extraArgs: string[]) =>
mockedRun(() => {
return main(['node', 'path', ...extraArgs])
})
.then(lineize)
it('prints version without blowing up', async ()=> {
const {stdout, stderr, log, exit} = await run('-V')
expect(stdout).toEqual([`1.0.0`])
expect(stderr).toEqual([])
expect(exit).toEqual([0])
expect(log).toEqual([])
})
it('prints help if not given argumnets' , async ()=> {
const {stdout, stderr, log, exit} = await run()
expect(stdout[0]).toEqual(`Usage: tysana [options] [command]`)
expect(stderr).toEqual([])
expect(exit).toEqual([0])
expect(log).toEqual([])
})
it('prints help if given unknown command', async () => {
const command = 'totally not a command'
const {stdout, stderr, log, exit} = await run(command)
expect(stdout).toEqual([])
expect(stderr).toEqual([])
expect(exit).toEqual([1])
expect(log).toEqual([
`Invalid command: ${command}`,
`See --help for a list of available commands.`,
])
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment