Skip to content

Instantly share code, notes, and snippets.

@rcmedeiros
Last active March 20, 2020 04:29
Show Gist options
  • Save rcmedeiros/f93de635c9443310f98172417419b535 to your computer and use it in GitHub Desktop.
Save rcmedeiros/f93de635c9443310f98172417419b535 to your computer and use it in GitHub Desktop.
Mocha capture stdout
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