Skip to content

The platform for continuously improving AI agents.

1.4 KB
Raw Blame
// @vitest-environment jsdom
// covers: console-logic
import { afterEach, describe, expect, it, vi } from "vitest";

import { whilePageVisible } from "./visible-stream";

let state: DocumentVisibilityState = "visible";
Object.defineProperty(document, "visibilityState", { configurable: true, get: () => state });

const show = (next: DocumentVisibilityState) => {
  state = next;
  document.dispatchEvent(new Event("visibilitychange"));
};

describe("whilePageVisible", () => {
  afterEach(() => {
    state = "visible";
  });

  it("closes the stream while the tab is hidden and opens one when it shows again", () => {
    const stop = vi.fn();
    const start = vi.fn(() => stop);
    const release = whilePageVisible(start);
    expect(start).toHaveBeenCalledTimes(1);

    show("hidden");
    expect(stop).toHaveBeenCalledTimes(1);
    show("hidden");
    expect(stop).toHaveBeenCalledTimes(1);

    show("visible");
    expect(start).toHaveBeenCalledTimes(2);
    show("visible");
    expect(start).toHaveBeenCalledTimes(2);

    release();
    expect(stop).toHaveBeenCalledTimes(2);
    show("hidden");
    show("visible");
    expect(start).toHaveBeenCalledTimes(2);
  });

  it("opens nothing for a tab that starts hidden", () => {
    state = "hidden";
    const start = vi.fn(() => () => {});
    const release = whilePageVisible(start);
    expect(start).not.toHaveBeenCalled();
    show("visible");
    expect(start).toHaveBeenCalledTimes(1);
    release();
  });
});