You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

53 lines
1.7 KiB

import { describe, expect, it, vi } from "vitest";
import type { QuestionListItem } from "@/lib/schema-adapter";
import { prefetchSectionsWithBoundedConcurrency } from "./section-prefetch";
function section(slug: string): QuestionListItem {
return { slug } as QuestionListItem;
}
describe("prefetchSectionsWithBoundedConcurrency", () => {
it("starts promptly and runs at most two section requests at once", async () => {
const sections = [section("one"), section("two"), section("three")];
const releases: Array<() => void> = [];
let activeRequests = 0;
let maximumActiveRequests = 0;
const prefetch = vi.fn(async () => {
activeRequests += 1;
maximumActiveRequests = Math.max(maximumActiveRequests, activeRequests);
await new Promise<void>((resolve) => releases.push(resolve));
activeRequests -= 1;
});
const queue = prefetchSectionsWithBoundedConcurrency(
sections,
prefetch,
() => false,
);
expect(prefetch).toHaveBeenCalledTimes(2);
expect(maximumActiveRequests).toBe(2);
releases.shift()?.();
await vi.waitFor(() => expect(prefetch).toHaveBeenCalledTimes(3));
expect(maximumActiveRequests).toBe(2);
releases.splice(0).forEach((release) => release());
await queue;
});
it("continues after a background request fails", async () => {
const prefetch = vi
.fn<(item: QuestionListItem) => Promise<void>>()
.mockRejectedValueOnce(new Error("offline"))
.mockResolvedValue(undefined);
await prefetchSectionsWithBoundedConcurrency(
[section("one"), section("two"), section("three")],
prefetch,
() => false,
);
expect(prefetch).toHaveBeenCalledTimes(3);
});
});