Procházet zdrojové kódy

Merge branch 'feature/fe_tests_saga' of Neca/HRCenter into FE_dev

pull/172/head
safet.purkovic před 3 roky
rodič
revize
b9adf81881

+ 36
- 0
src/__tests__/ReduxTests/inviteDialog.test.js Zobrazit soubor

expect(dispatchedActions).toContainEqual(inviteUserSuccess()); expect(dispatchedActions).toContainEqual(inviteUserSuccess());
}); });


it("should run inviteUser saga function with actions and call response success", async () => {
const dispatchedActions = [];

// we don't want to perform an actual api call in our tests
// so we will mock the getAllUsers api with jest
// this will mutate the dependency which we may reset if other tests
// are dependent on it
const mockedCall = { data: { message: "Link has been sent!" } };
api.inviteUserRequest = jest.fn(() => Promise.resolve(mockedCall));

const fakeStore = {
getState: () => ({
invite: {
isSuccess: false,
errorMessage: "",
},
}),
dispatch: (action) => dispatchedActions.push(action),
};

const mock = jest.fn()

// wait for saga to complete
await runSaga(fakeStore, invite, {
payload: {
invite:{
firstName: "st",
lastName: "Test",
email: "test@dilig.net",},
handleApiResponseSuccess: mock
},
}).done;

expect(mock).toHaveBeenCalled();
});

it("should run inviteUser saga function with error actions in case of api error", async () => { it("should run inviteUser saga function with error actions in case of api error", async () => {
const dispatchedActions = []; const dispatchedActions = [];



+ 89
- 9
src/__tests__/ReduxTests/processesReducer.test.js Zobrazit soubor

finishProcess, finishProcess,
changeStatus, changeStatus,
changeInterviewer, changeInterviewer,
getApplicantProcesses,
} from "../../store/saga/processSaga"; } from "../../store/saga/processSaga";
import { import {
setProcesses, setProcesses,
setUpdateStatusErr, setUpdateStatusErr,
setUpdateStatusSucc, setUpdateStatusSucc,
} from "../../store/actions/processes/processAction"; } from "../../store/actions/processes/processAction";
import {
setApplicant,
setApplicantError,
} from "../../store/actions/processes/applicantAction";


describe("SelectionProcessPage render tests", () => { describe("SelectionProcessPage render tests", () => {
const cont = ( const cont = (
expect(dispatchedActions).toContainEqual(setProcesses(filteredData)); expect(dispatchedActions).toContainEqual(setProcesses(filteredData));
}); });


it("should handle error in case of exception", async () => {
const dispatchedActions = [];

const filter = {
statuses: ["Zakazan", "Odrađen"],
dateStart: new Date(2023, 0, 5),
dateEnd: new Date(2024, 1, 1),
};

const error = {
response: {
data: { message: mockState.selections.fetchSelectionsErrorMessage },
},
};
api.getAllFilteredProcessesReq = jest.fn(() => Promise.reject(error));

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

// wait for saga to complete
await runSaga(fakeStore, getFilteredProcesses, filter).done;
expect(dispatchedActions).toContainEqual(
setProcessesError(error.response.data.message)
);
});

it("should handle process to set it done in case of success", async () => { it("should handle process to set it done in case of success", async () => {
// we push all dispatched actions to make assertions easier // we push all dispatched actions to make assertions easier
// and our tests less brittle // and our tests less brittle


it("should handle process status update error if exception is thrown", async () => { it("should handle process status update error if exception is thrown", async () => {
const dispatchedActions = []; const dispatchedActions = [];
const error = { const error = {
response: { response: {
data: { message: mockState.selections.fetchSelectionsErrorMessage }, data: { message: mockState.selections.fetchSelectionsErrorMessage },
}, },
}; };
api.updateStatus = jest.fn(() => Promise.reject(error)); api.updateStatus = jest.fn(() => Promise.reject(error));


const fakeStore = { const fakeStore = {
processId: 2, processId: 2,
}, },
// responseHandler: apiSuccess, // responseHandler: apiSuccess,
}
},
}).done; }).done;


expect(api.updateInterviewer.mock.calls.length).toBe(1); expect(api.updateInterviewer.mock.calls.length).toBe(1);
dispatch: (action) => dispatchedActions.push(action), dispatch: (action) => dispatchedActions.push(action),
}; };


const mockfn = jest.fn()
const mockfn = jest.fn();


// wait for saga to complete // wait for saga to complete
await runSaga(fakeStore, changeInterviewer, { await runSaga(fakeStore, changeInterviewer, {
processId: 2, processId: 2,
}, },
responseHandler: mockfn, responseHandler: mockfn,
}
},
}).done; }).done;


expect(mockfn).toHaveBeenCalled(); expect(mockfn).toHaveBeenCalled();
processId: 2, processId: 2,
}, },
// responseHandler: mockfn, // responseHandler: mockfn,
}
},
}).done; }).done;


expect(api.updateInterviewer.mock.calls.length).toBe(1); expect(api.updateInterviewer.mock.calls.length).toBe(1);
}; };
api.updateInterviewer = jest.fn(() => Promise.reject(error)); api.updateInterviewer = jest.fn(() => Promise.reject(error));


const mockfn = jest.fn()
const mockfn = jest.fn();


const fakeStore = { const fakeStore = {
getState: () => mockState.selections.processes, getState: () => mockState.selections.processes,
processId: 2, processId: 2,
}, },
responseHandler: mockfn, responseHandler: mockfn,
}
},
}).done; }).done;


expect(mockfn).not.toHaveBeenCalled(); expect(mockfn).not.toHaveBeenCalled();
}); });

it("should handle applicant processess if succeeded", async () => {
const dispatchedActions = [];
const mockedCall = { data: {} };
api.getProcessesOfApplicant = jest.fn(() => Promise.resolve(mockedCall));

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

// wait for saga to complete
await runSaga(fakeStore, getApplicantProcesses, {
payload: {
id: 1,
},
}).done;

expect(api.getProcessesOfApplicant.mock.calls.length).toBe(1);
expect(dispatchedActions).toContainEqual(setApplicant(mockedCall.data));
});

it("should handle applicant processess error if exception is thrown", async () => {
const dispatchedActions = [];
const error = {
response: {
data: { message: mockState.selections.fetchSelectionsErrorMessage },
},
};
api.getProcessesOfApplicant = jest.fn(() => Promise.reject(error));

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

// wait for saga to complete
await runSaga(fakeStore, getApplicantProcesses, {
payload: {
id: 1,
},
}).done;

expect(api.getProcessesOfApplicant.mock.calls.length).toBe(1);
expect(dispatchedActions).toContainEqual(
setApplicantError(error.response.data.message)
);
});
}); });

+ 80
- 12
src/__tests__/ReduxTests/registerSagaTest.test.js Zobrazit soubor

import { Router } from "react-router-dom"; import { Router } from "react-router-dom";
import history from "../../store/utils/history"; import history from "../../store/utils/history";
import { mockState } from "../../mockState"; import { mockState } from "../../mockState";
import * as api from '../../request/registerRequest'
import * as api from "../../request/registerRequest";
import { render } from "@testing-library/react"; import { render } from "@testing-library/react";
import UserDetails from "../../pages/UsersPage/UserDetails"; import UserDetails from "../../pages/UsersPage/UserDetails";
import ColorModeProvider from "../../context/ColorModeContext"; import ColorModeProvider from "../../context/ColorModeContext";
import { USER_DETAILS_REQ } from "../../store/actions/users/usersActionConstants";
import { import {
USER_DETAILS_REQ,
} from "../../store/actions/users/usersActionConstants";
import { registerSuccess } from "../../store/actions/register/registerActions";
registerError,
registerSuccess,
} from "../../store/actions/register/registerActions";
import { runSaga } from "redux-saga"; import { runSaga } from "redux-saga";
import { userDetails } from "../../store/saga/usersSaga"; import { userDetails } from "../../store/saga/usersSaga";
import { registerUser } from "../../store/saga/registerSaga"; import { registerUser } from "../../store/saga/registerSaga";
import * as helper from "../../util/helpers/rejectErrorCodeHelper";


describe("UserDetails reducer tests", () => { describe("UserDetails reducer tests", () => {
let spyOnUseSelector;
let spyOnUseSelector;
let spyOnUseDispatch; let spyOnUseDispatch;
let mockDispatch; let mockDispatch;




await runSaga(fakeStore, registerUser, { await runSaga(fakeStore, registerUser, {
payload: { payload: {
password:'',
email:'',
confirm:'',
position:'',
linkedIn:'',
phone:'',
token:'',
model: {
password: "",
email: "",
confirm: "",
position: "",
linkedIn: "",
phone: "",
token: "",
},
}, },
}).done; }).done;


expect(api.register.mock.calls.length).toBe(1); expect(api.register.mock.calls.length).toBe(1);
expect(dispatchedActions).toContainEqual(registerSuccess()); expect(dispatchedActions).toContainEqual(registerSuccess());
}); });

it("should call handleApiResponseSuccess", async () => {
const dispatchedActions = [];

api.register = jest.fn(() => Promise.resolve());

const fakeStore = {
getState: () => ({
isSuccess: false,
errorMessage: "",
}),
dispatch: (action) => dispatchedActions.push(action),
};

const mockFn = jest.fn()

await runSaga(fakeStore, registerUser, {
payload: {
model: {
password: "",
email: "",
confirm: "",
position: "",
linkedIn: "",
phone: "",
token: "",
},
handleApiResponseSuccess: mockFn
},
}).done;

expect(mockFn).toHaveBeenCalled();
});

it("should handle register error", async () => {
const dispatchedActions = [];

const error = { response: { data: { message: "Error" } } };
helper.rejectErrorCodeHelper = jest.fn(() => "Error")
api.register = jest.fn(() => Promise.reject(error));

const fakeStore = {
getState: () => ({
isSuccess: false,
errorMessage: "",
}),
dispatch: (action) => dispatchedActions.push(action),
};

await runSaga(fakeStore, registerUser, {
payload: {
password: "",
email: "",
confirm: "",
position: "",
linkedIn: "",
phone: "",
token: "",
},
}).done;

expect(api.register.mock.calls.length).toBe(1);
expect(dispatchedActions).toContainEqual(registerError("Error"));
});
}); });

+ 26
- 1
src/__tests__/ReduxTests/userDetailsReducer.test.js Zobrazit soubor

USER_DETAILS_REQ, USER_DETAILS_REQ,
} from "../../store/actions/users/usersActionConstants"; } from "../../store/actions/users/usersActionConstants";
import { userDetails } from "../../store/saga/usersSaga"; import { userDetails } from "../../store/saga/usersSaga";
import { stateUserDetailsSuccess } from "../../store/actions/users/usersActions";
import { stateUserDetailsSuccess, userDetailsError } from "../../store/actions/users/usersActions";
import { runSaga } from "redux-saga"; import { runSaga } from "redux-saga";
import * as helper from "../../util/helpers/rejectErrorCodeHelper";


jest.mock("react-router-dom", () => ({ jest.mock("react-router-dom", () => ({
...jest.requireActual("react-router-dom"), ...jest.requireActual("react-router-dom"),
dispatch: (action) => dispatchedActions.push(action), dispatch: (action) => dispatchedActions.push(action),
}; };


const mock = jest.fn()

await runSaga(fakeStore, userDetails, { await runSaga(fakeStore, userDetails, {
payload: { payload: {
id: 1, id: 1,
handleApiResponseSuccess: mock
}, },
}).done; }).done;


expect(api.userDetailsRequest.mock.calls.length).toBe(1); expect(api.userDetailsRequest.mock.calls.length).toBe(1);
expect(mock).toHaveBeenCalled();
expect(dispatchedActions).toContainEqual(stateUserDetailsSuccess(mockState.user.user)); expect(dispatchedActions).toContainEqual(stateUserDetailsSuccess(mockState.user.user));
}); });

it("should handle error if exception occurs", async () => {
const dispatchedActions = [];
helper.rejectErrorCodeHelper = jest.fn(() => "Error");
api.userDetailsRequest = jest.fn(() => Promise.reject({ response: {data:{message:"Error"}} }));

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

await runSaga(fakeStore, userDetails, {
payload: {
id: 1,
},
}).done;

expect(api.userDetailsRequest.mock.calls.length).toBe(1);
expect(dispatchedActions).toContainEqual(userDetailsError("Error"));
});
}); });

+ 75
- 2
src/__tests__/ReduxTests/userManagementReducer.test.js Zobrazit soubor

import { FETCH_USERS_REQ } from "../../store/actions/users/usersActionConstants"; import { FETCH_USERS_REQ } from "../../store/actions/users/usersActionConstants";
import { import {
deleteStateUser, deleteStateUser,
deleteUserError,
setEnableUsers, setEnableUsers,
setEnableUsersError,
setUsers, setUsers,
setUsersError, setUsersError,
toggleSingleUser, toggleSingleUser,
} from "../../store/actions/users/usersActions"; } from "../../store/actions/users/usersActions";
import { deleteUser, enableUser, getUsers } from "../../store/saga/usersSaga"; import { deleteUser, enableUser, getUsers } from "../../store/saga/usersSaga";
import { useTranslation } from "react-i18next";

import * as helper from "../../util/helpers/rejectErrorCodeHelper";
describe("User management reducer tests", () => { describe("User management reducer tests", () => {
const cont = ( const cont = (
<redux.Provider store={store}> <redux.Provider store={store}>
dispatch: (action) => dispatchedActions.push(action), dispatch: (action) => dispatchedActions.push(action),
}; };


const mock = jest.fn();

await runSaga(fakeStore, enableUser, { await runSaga(fakeStore, enableUser, {
payload: { payload: {
id: 1, id: 1,
handleApiResponseSuccess: mock,
}, },
}).done; }).done;


expect(api.enableUserRequest.mock.calls.length).toBe(1); expect(api.enableUserRequest.mock.calls.length).toBe(1);
expect(mock).toHaveBeenCalled();
expect(dispatchedActions).toContainEqual(setEnableUsers()); expect(dispatchedActions).toContainEqual(setEnableUsers());
expect(dispatchedActions).toContainEqual(toggleSingleUser()); expect(dispatchedActions).toContainEqual(toggleSingleUser());
}); });


it("should handle enableUser saga errors", async () => {
const dispatchedActions = [];
helper.rejectErrorCodeHelper = jest.fn(() => "Server error");

api.enableUserRequest = jest.fn(() =>
Promise.reject({ response: { data: { message: "Server error" } } })
);
const fakeStore = {
getState: () => mockState.users,
dispatch: (action) => dispatchedActions.push(action),
};

await runSaga(fakeStore, enableUser, {
payload: {
id: 1,
},
}).done;

expect(dispatchedActions).toContainEqual(setEnableUsersError("Server error"));
});

it("should run deleteUser saga function with actions", async () => { it("should run deleteUser saga function with actions", async () => {
const dispatchedActions = []; const dispatchedActions = [];


expect(api.deleteUserRequest.mock.calls.length).toBe(1); expect(api.deleteUserRequest.mock.calls.length).toBe(1);
expect(dispatchedActions).toContainEqual(deleteStateUser(1)); expect(dispatchedActions).toContainEqual(deleteStateUser(1));
}); });

it("should run deleteUser saga function with actions and call response success", async () => {
const dispatchedActions = [];

api.deleteUserRequest = jest.fn(() => Promise.resolve({ data: 1 }));

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

const mock = jest.fn();

await runSaga(fakeStore, deleteUser, {
payload: {
id: 1,
handleApiResponseSuccess: mock,
},
}).done;

expect(api.deleteUserRequest.mock.calls.length).toBe(1);
expect(mock).toHaveBeenCalled();
});

it("should handle error when deleteUser runs", async () => {
const dispatchedActions = [];

helper.rejectErrorCodeHelper = jest.fn(() => "Server error");

api.deleteUserRequest = jest.fn(() =>
Promise.reject({ response: { data: { message: "Server error" } } })
);

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

await runSaga(fakeStore, deleteUser, {
payload: {
id: 1,
},
}).done;

expect(dispatchedActions).toContainEqual(deleteUserError("Server error"));
});
}); });

+ 26
- 0
src/__tests__/UITests/mainContainer.test.js Zobrazit soubor

import { render, screen } from "@testing-library/react";
import { Provider } from "react-redux";
import { Router } from "react-router-dom";
import AppRoutes from "../../AppRoutes";
import MainContainer from "../../components/Section/MainContainer";
import store from "../../store";
import history from "../../store/utils/history";

describe("main container tests", () => {
const cont = (
<Provider store={store}>
<Router history={history}>
<MainContainer>
<AppRoutes />
</MainContainer>
</Router>
</Provider>
);

it("Should render", () => {
const {container} = render(cont);

expect(screen.queryByTestId('default-route-div')).toBeDefined()
expect(container.getElementsByClassName('h-withHeader')[0]).not.toBeDefined()
});
});

+ 2
- 2
src/components/Section/MainContainer.js Zobrazit soubor

const { pathname } = useLocation(); const { pathname } = useLocation();


return urls.includes(pathname) ? ( return urls.includes(pathname) ? (
<div className="">{children}</div>
<div data-testid="default-route-div" className="">{children}</div>
) : pathname === "/register" ? ( ) : pathname === "/register" ? (
<FormProvider> <FormProvider>
<div className="">{children}</div> <div className="">{children}</div>
) : ( ) : (
<div className=""> <div className="">
<Navbar /> <Navbar />
<div className={pathname === CREATE_AD_PAGE ? "" : 'h-withHeader'}>
<div className={pathname === CREATE_AD_PAGE ? "" : "h-withHeader"}>
{children} {children}
</div> </div>
</div> </div>

+ 1
- 3
src/store/saga/registerSaga.js Zobrazit soubor

try { try {
yield call(register, payload.model); yield call(register, payload.model);
yield put(registerSuccess()); yield put(registerSuccess());
// console.log('ovde 1')
if(payload.handleApiResponseSuccess){ if(payload.handleApiResponseSuccess){
// console.log('ovde 2')
yield call(payload.handleApiResponseSuccess) yield call(payload.handleApiResponseSuccess)
} }
} catch (error) { } catch (error) {
} }
} }
} }

export default function* registerSaga() { export default function* registerSaga() {
yield all([ yield all([
takeEvery(REGISTER_REQUEST, registerUser), takeEvery(REGISTER_REQUEST, registerUser),

Načítá se…
Zrušit
Uložit