import * as redux from "react-redux";
import store from "../../store";
import { Router } from "react-router-dom";
import history from "../../store/utils/history";
import { mockState } from "../../mockState";
import { render } from "@testing-library/react";
import * as api from "../../request/usersRequest";
import { runSaga } from "redux-saga";
import {
  setUsers,
  setUsersError,
} from "../../store/actions/users/usersActions";
import { FETCH_USERS_REQ } from "../../store/actions/users/usersActionConstants";
import { getUsers } from "../../store/saga/usersSaga";
import * as helper from "../../util/helpers/rejectErrorCodeHelper";
import UsersPage from "../../pages/UsersPage/UsersPage";

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

  let spyOnUseSelector;
  let spyOnUseDispatch;
  let mockDispatch;

  beforeEach(() => {
    // Mock useSelector hook
    spyOnUseSelector = jest.spyOn(redux, "useSelector");
    spyOnUseSelector.mockReturnValueOnce(mockState.users);

    // Mock useDispatch hook
    spyOnUseDispatch = jest.spyOn(redux, "useDispatch");

    // Mock dispatch function returned from useDispatch
    mockDispatch = jest.fn();
    spyOnUseDispatch.mockReturnValue(mockDispatch);
  });

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

  it("Should dispatch get users request when rendered", () => {
    render(cont);
    expect(mockDispatch).toHaveBeenCalledWith({
      type: FETCH_USERS_REQ,
    });
  });

  it("should load and handle users in case of success", async () => {
    const dispatchedActions = [];

    const mockedCall = { data: mockState.users };
    api.getAllUsers = jest.fn(() => Promise.resolve(mockedCall));

    const fakeStore = {
      getState: () => mockState.users,
      dispatch: (action) => dispatchedActions.push(action),
    };

    await runSaga(fakeStore, getUsers).done;
    expect(api.getAllUsers.mock.calls.length).toBe(1);
    expect(dispatchedActions).toContainEqual(setUsers(mockedCall.data));
  });

  it("should handle users load errors in case of failure", async () => {
    const dispatchedActions = [];

    helper.rejectErrorCodeHelper = jest.fn(
      () => mockState.users.fetchUsersErrorMessage
    );

    const error = {
      response: {
        data: { message: mockState.users.fetchUsersErrorMessage },
      },
    };
    api.getAllUsers = jest.fn(() => Promise.reject(error));

    const fakeStore = {
      getState: () => mockState.users,
      dispatch: (action) => dispatchedActions.push(action),
    };

    await runSaga(fakeStore, getUsers).done;
    expect(api.getAllUsers.mock.calls.length).toBe(1);
    expect(dispatchedActions).toContainEqual(
      setUsersError(error.response.data.message)
    );
  });
});
