terminal-writer.test.ts 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import { describe, expect, test } from "bun:test"
  2. import { terminalWriter } from "./terminal-writer"
  3. describe("terminalWriter", () => {
  4. test("buffers and flushes once per schedule", () => {
  5. const calls: string[] = []
  6. const scheduled: VoidFunction[] = []
  7. const writer = terminalWriter(
  8. (data, done) => {
  9. calls.push(data)
  10. done?.()
  11. },
  12. (flush) => scheduled.push(flush),
  13. )
  14. writer.push("a")
  15. writer.push("b")
  16. writer.push("c")
  17. expect(calls).toEqual([])
  18. expect(scheduled).toHaveLength(1)
  19. scheduled[0]?.()
  20. expect(calls).toEqual(["abc"])
  21. })
  22. test("flush is a no-op when empty", () => {
  23. const calls: string[] = []
  24. const writer = terminalWriter(
  25. (data, done) => {
  26. calls.push(data)
  27. done?.()
  28. },
  29. (flush) => flush(),
  30. )
  31. writer.flush()
  32. expect(calls).toEqual([])
  33. })
  34. test("flush waits for pending write completion", () => {
  35. const calls: string[] = []
  36. let done: VoidFunction | undefined
  37. const writer = terminalWriter(
  38. (data, finish) => {
  39. calls.push(data)
  40. done = finish
  41. },
  42. (flush) => flush(),
  43. )
  44. writer.push("a")
  45. let settled = false
  46. writer.flush(() => {
  47. settled = true
  48. })
  49. expect(calls).toEqual(["a"])
  50. expect(settled).toBe(false)
  51. done?.()
  52. expect(settled).toBe(true)
  53. })
  54. })