import React from "react";
import "@testing-library/jest-dom";
import { act, render, screen } from "@testing-library/react";

import { useViewResource } from "./hooks/useViewResource";

function deferred<T>() {
  let resolve!: (value: T) => void;
  const promise = new Promise<T>((next) => { resolve = next; });
  return { promise, resolve };
}

it("ignores an older request that completes after a newer dependency load", async () => {
  const first = deferred<string>();
  const second = deferred<string>();
  const load = jest.fn((key: string) => key === "first" ? first.promise : second.promise);

  function Probe({ query }: { query: string }) {
    const resource = useViewResource(() => load(query), {
      initialData: "empty",
      errorMessage: "Unable to load.",
      deps: [query],
    });
    return <div>{resource.data}</div>;
  }

  const view = render(<Probe query="first" />);
  view.rerender(<Probe query="second" />);

  await act(async () => { second.resolve("new result"); });
  expect(screen.getByText("new result")).toBeInTheDocument();

  await act(async () => { first.resolve("stale result"); });
  expect(screen.getByText("new result")).toBeInTheDocument();
  expect(screen.queryByText("stale result")).not.toBeInTheDocument();
});
