Skip to content

Commit

Permalink
fix: dont use stream if test
Browse files Browse the repository at this point in the history
  • Loading branch information
mdonnalley committed Oct 8, 2024
1 parent 74c4e34 commit 1d44eb3
Showing 1 changed file with 19 additions and 10 deletions.
29 changes: 19 additions & 10 deletions src/table.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -393,6 +393,7 @@ export function Skeleton(props: React.PropsWithChildren & {readonly height?: num
*/
class Stream extends WriteStream {
private frames: string[] = []

public lastFrame(): string | undefined {
return this.frames.filter((f) => stripAnsi(f) !== '').at(-1)
}
Expand All @@ -403,23 +404,31 @@ class Stream extends WriteStream {
}
}

function makeOptions() {
if (process.env.NODE_ENV === 'test') {
return {}
class Output {
public stream: Stream | WriteStream

public constructor(fd = 1) {
this.stream = process.env.NODE_ENV === 'test' ? process.stdout : new WriteStream(fd)
}

return {stdout: new Stream(1)}
public maybePrintLastFrame() {
if (this.stream instanceof Stream) {
process.stdout.write(`${this.stream.lastFrame()}\n`)
} else {
process.stdout.write('\n')
}
}
}

/**
* Renders a table with the given data.
* @param options see {@link TableOptions}
*/
export function printTable<T extends Record<string, unknown>>(options: TableOptions<T>): void {
const stdout = new Stream(0)
const instance = render(<Table {...options} />, {...makeOptions()})
const output = new Output()
const instance = render(<Table {...options} />, {stdout: output.stream})
instance.unmount()
process.stdout.write(`${stdout.lastFrame()}\n`)
output.maybePrintLastFrame()
}

function Container(props: ContainerProps) {
Expand All @@ -434,7 +443,7 @@ export function printTables<T extends Record<string, unknown>[]>(
tables: {[P in keyof T]: TableOptions<T[P]>},
options?: Omit<ContainerProps, 'children'>,
): void {
const stdout = new Stream(0)
const output = new Output()
const leftMargin = options?.marginLeft ?? options?.margin ?? 0
const rightMargin = options?.marginRight ?? options?.margin ?? 0
const columns = process.stdout.columns - (leftMargin + rightMargin)
Expand All @@ -451,8 +460,8 @@ export function printTables<T extends Record<string, unknown>[]>(
<Table key={sha1(table)} {...table} />
))}
</Container>,
{...makeOptions()},
{stdout: output.stream},
)
instance.unmount()
process.stdout.write(`${stdout.lastFrame()}\n`)
output.maybePrintLastFrame()
}

0 comments on commit 1d44eb3

Please sign in to comment.