import Polling from "./polling";

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

describe("Polling", () => {
  beforeEach(() => {
    jest.clearAllMocks();
  });

  it("starts and ends polling", async () => {
    const callback = () => Promise.resolve();
    const poll = new Polling(callback, 100);
    const spy = jest.spyOn(poll, "callback");
    poll.start();
    await sleep(501); // +1 for safety
    poll.end();
    await sleep(500);
    expect(spy).toHaveBeenCalledTimes(5);
  });

  it("async polling", async () => {
    const callback = () => sleep(100);
    const poll = new Polling(callback, 100);
    const spy = jest.spyOn(poll, "callback");
    poll.start();
    await sleep(1001); // +1 for safety
    expect(spy).toHaveBeenCalledTimes(5);
  });
});
