import { delay } from "./delay";

describe("delay", () => {
  beforeEach(() => {
    vi.useFakeTimers();
  });

  afterEach(() => {
    vi.useRealTimers();
  });

  it("should resolve after specified delay", async () => {
    const promise = delay(1000);
    vi.advanceTimersByTime(1000);
    await promise;
  });

  it("should reject when aborted", async () => {
    const controller = new AbortController();
    const promise = delay(1000, { signal: controller.signal });

    controller.abort();

    await expect(promise).rejects.toThrow("Aborted");
    await expect(promise).rejects.toBeInstanceOf(DOMException);
  });

  it("should not resolve before the specified time", async () => {
    const promise = delay(1000);
    vi.advanceTimersByTime(500);

    const resolved = await Promise.race([promise, Promise.resolve("early")]);

    expect(resolved).toBe("early");
  });
});
