jest.mock("../../services/vehiclesAPI");

import {
  render,
  cleanup,
  screen,
  fireEvent,
  waitFor,
  act,
} from "@testing-library/react";
import { CANSignalProvider, useCANSignalContext } from "./CANSignalsContext";

const checkSignalsResults = (filters) => {
  expect(screen.getByTestId("signals").innerHTML).toEqual(filters);
};

describe("CANSignalsContext", () => {
  describe("getSignals", () => {
    beforeEach(() => {
      jest.useFakeTimers("setInterval");
      const TestComp = () => {
        const { signals, setVIN, setDelayIndex } = useCANSignalContext();
        setDelayIndex(0);

        return (
          <>
            <div data-testid="signals">{JSON.stringify(signals)}</div>
            <button
              data-testid="getSignals"
              onClick={() => { setVIN("TESTVIN1234567890") }}
            />
          </>
        );
      };
      render(
        <CANSignalProvider>
          <TestComp />
        </CANSignalProvider>
      );
    });

    afterEach(() => {
      jest.useRealTimers();
      cleanup();
    });

    it("initial state", () => {
      checkSignalsResults("[]");
    });

    it("getSignals", async () => {
      // eslint-disable-next-line testing-library/no-unnecessary-act
      await act(async () => {
        fireEvent.click(screen.getByTestId("getSignals"));
        await waitFor(() =>
          expect(screen.getByTestId("signals").innerHTML).toBe("[]")
        );
        jest.advanceTimersByTime(3001);
      })

      await waitFor(() => {
        return expect(screen.getByTestId("signals").innerHTML).not.toBe("[]");
      });

      checkSignalsResults(JSON.stringify(expectedSignalsData));
    });
  });
});

const expectedSignalsData = [
  {
    timestamp: "7/14/2021 8:09:40 PM",
    signal: "signal",
    value: 123
  },
];
