import * as redux from "react-redux";
import store from "../../store";
import { Router } from "react-router-dom";
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import history from "../../store/utils/history";
import ForgotPasswordPage from "../../pages/ForgotPasswordPage/ForgotPasswordPageMUI";

describe("ForgotPasswordPage render tests", () => {
  const cont = (
    <redux.Provider store={store}>
      <Router history={history}>
        <ForgotPasswordPage />
      </Router>
    </redux.Provider>
  );

  let spyOnUseDispatch;
  let mockDispatch;

  beforeEach(() => {
    spyOnUseDispatch = jest.spyOn(redux, "useDispatch");
    mockDispatch = jest.fn();
    spyOnUseDispatch.mockReturnValue(mockDispatch);
  });

  afterEach(() => {
    jest.restoreAllMocks();
  });

  it("Should render", () => {
    const { container } = render(cont);
    expect(
      container.getElementsByClassName("c-login-container")[0]
    ).toBeDefined();
  });

  it("Should render login logo", () => {
    const { container } = render(cont);
    expect(container.getElementsByClassName("login-logo")[0]).toBeDefined();
  });

  it("Should render header", () => {
    const { container } = render(cont);
    expect(
      container
        .getElementsByClassName("c-login-container")[0]
        .querySelector("h")
    ).toBeDefined();
  });

  it("Should render paragraph", () => {
    const { container } = render(cont);
    expect(
      container
        .getElementsByClassName("c-login-container")[0]
        .querySelector("p")
    ).toBeDefined();
  });

  it("Should render email input", () => {
    render(cont);
    expect(screen.getByTestId("email-input")).toBeDefined();
  });

  it("Should render submit button", () => {
    const { container } = render(cont);
    expect(container.getElementsByClassName("c-btn")[0]).toBeDefined();
  });

  it("Should render link for going to login page", () => {
    render(cont);
    expect(screen.getByTestId("back-link")).toBeDefined();
  });

  it("Should render dilig logo", () => {
    render(cont);
    expect(screen.getByTestId("dilig-logo")).toBeDefined();
  });

  it("Should not dispatch function because input for email is empty", async () => {
    const { container } = render(cont);
    fireEvent.click(container.getElementsByClassName("c-btn")[0]);
    await waitFor(() => expect(mockDispatch).toBeCalledTimes(0));
  });

  it("Should dispatch function becxause input for email is not empty", async () => {
    const { container } = render(cont);
    fireEvent.change(screen.getByTestId("email-input"), {
      target: { value: "dzenis@dilig.net" },
    });
    fireEvent.click(container.getElementsByClassName("c-btn")[0]);
    await waitFor(() => expect(mockDispatch).toBeCalledTimes(1));
  });
});
