Last active
March 20, 2020 04:29
-
-
Save rcmedeiros/f93de635c9443310f98172417419b535 to your computer and use it in GitHub Desktop.
Mocha capture stdout
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { WriteStream } from 'tty'; | |
type callback = (error: Error | null | undefined) => void; | |
export interface Capture { | |
unhook: () => void; | |
captured: () => string; | |
} | |
export const captureStream = (stream: WriteStream): Capture => { | |
const oldWrite = stream.write; | |
let output = ''; | |
stream.write = (chunk: unknown, encoding: string | callback, cb?: callback): boolean => { | |
output += chunk.toString(); // chunk is a String or Buffer | |
return oldWrite.apply(stream, cb ? [chunk, encoding, cb] : [chunk, encoding, cb]); | |
} | |
return { | |
unhook: (): void => { | |
stream.write = oldWrite; | |
}, | |
captured: (): string => { | |
return output; | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment