| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697 |
- 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 StatsPage from "../../pages/StatsPage/StatsPage";
- import * as api from "../../request/statsRequests";
- import { runSaga } from "redux-saga";
- import {
- getStatsSuccess,
- getStatsError,
- } from "../../store/actions/stats/statsActions";
- import { FETCH_STATS_REQ } from "../../store/actions/stats/statsActionConstants";
- import { getAppStats } from "../../store/saga/statsSaga";
- import * as helper from "../../util/helpers/rejectErrorCodeHelper";
-
- describe("Stats reducer tests", () => {
- const cont = (
- <redux.Provider store={store}>
- <Router history={history}>
- <StatsPage />
- </Router>
- </redux.Provider>
- );
-
- let spyOnUseSelector;
- let spyOnUseDispatch;
- let mockDispatch;
-
- beforeEach(() => {
- // Mock useSelector hook
- spyOnUseSelector = jest.spyOn(redux, "useSelector");
- spyOnUseSelector.mockReturnValueOnce(mockState);
-
- // 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 stats request when rendered", () => {
- render(cont);
- expect(mockDispatch).toHaveBeenCalledWith({
- type: FETCH_STATS_REQ,
- });
- });
-
- it("should load and handle stats in case of success", async () => {
- const dispatchedActions = [];
-
- const mockedCall = { data: mockState };
- api.getStats = jest.fn(() => Promise.resolve(mockedCall));
-
- const fakeStore = {
- getState: () => mockState,
- dispatch: (action) => dispatchedActions.push(action),
- };
-
- await runSaga(fakeStore, getAppStats).done;
- expect(api.getStats.mock.calls.length).toBe(1);
- expect(dispatchedActions).toContainEqual(getStatsSuccess(mockedCall.data));
- });
-
- it("should handle stats load errors in case of failure", async () => {
- const dispatchedActions = [];
-
- helper.rejectErrorCodeHelper = jest.fn(
- () => mockState.stats.fetchStatsErrorMessage
- );
-
- const error = {
- response: {
- data: { message: mockState.stats.fetchStatsErrorMessage },
- },
- };
- api.getStats = jest.fn(() => Promise.reject(error));
-
- const fakeStore = {
- getState: () => mockState,
- dispatch: (action) => dispatchedActions.push(action),
- };
-
- await runSaga(fakeStore, getAppStats).done;
-
- expect(api.getStats.mock.calls.length).toBe(1);
- expect(dispatchedActions).toContainEqual(
- getStatsError(error.response.data.message)
- );
- });
- });
|