




















@@ -1,12 +1,27 @@
1-import { describe, expect, it, vi } from "vitest";
1+import { describe, expect, it } from "vitest";
22import { createSafeStreamWriter } from "./stream-writer.js";
334+function createSpy<Args extends unknown[], ReturnValue>(
5+implementation?: (...args: Args) => ReturnValue,
6+) {
7+const calls: Args[] = [];
8+const spy = (...args: Args) => {
9+calls.push(args);
10+return implementation?.(...args) as ReturnValue;
11+};
12+spy.calls = calls;
13+spy.clear = () => {
14+calls.length = 0;
15+};
16+return spy;
17+}
18+419describe("createSafeStreamWriter", () => {
520it("signals broken pipes and closes the writer", () => {
6-const onBrokenPipe = vi.fn();
21+const onBrokenPipe = createSpy<[], void>();
722const writer = createSafeStreamWriter({ onBrokenPipe });
823const stream = {
9-write: vi.fn(() => {
24+write: createSpy<[string], boolean>(() => {
1025const err = new Error("EPIPE") as NodeJS.ErrnoException;
1126err.code = "EPIPE";
1227throw err;
@@ -15,15 +30,15 @@ describe("createSafeStreamWriter", () => {
15301631expect(writer.writeLine(stream, "hello")).toBe(false);
1732expect(writer.isClosed()).toBe(true);
18-expect(onBrokenPipe).toHaveBeenCalledTimes(1);
33+expect(onBrokenPipe.calls).toHaveLength(1);
193420-onBrokenPipe.mockClear();
35+onBrokenPipe.clear();
2136expect(writer.writeLine(stream, "again")).toBe(false);
22-expect(onBrokenPipe).toHaveBeenCalledTimes(0);
37+expect(onBrokenPipe.calls).toHaveLength(0);
2338});
24392540it("treats broken pipes from beforeWrite as closed", () => {
26-const onBrokenPipe = vi.fn();
41+const onBrokenPipe = createSpy<[], void>();
2742const writer = createSafeStreamWriter({
2843 onBrokenPipe,
2944beforeWrite: () => {
@@ -32,10 +47,12 @@ describe("createSafeStreamWriter", () => {
3247throw err;
3348},
3449});
35-const stream = { write: vi.fn(() => true) } as unknown as NodeJS.WriteStream;
50+const stream = {
51+write: createSpy<[string], boolean>(() => true),
52+} as unknown as NodeJS.WriteStream;
36533754expect(writer.write(stream, "hi")).toBe(false);
3855expect(writer.isClosed()).toBe(true);
39-expect(onBrokenPipe).toHaveBeenCalledTimes(1);
56+expect(onBrokenPipe.calls).toHaveLength(1);
4057});
4158});
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。