├── .env ├── .eslintignore ├── src ├── react-app-env.d.ts ├── app │ ├── components │ │ ├── CustomCheckbox │ │ │ ├── CustomCheckbox.module.css │ │ │ ├── CustomCheckbox.tsx │ │ │ └── CustomCheckbox.test.tsx │ │ ├── CardFooterWrapper │ │ │ ├── CardFooterWrapper.tsx │ │ │ └── CardFooterWrapper.module.css │ │ ├── App │ │ │ ├── App.css │ │ │ ├── App.tsx │ │ │ ├── App.test.tsx │ │ │ └── __snapshots__ │ │ │ │ └── App.test.tsx.snap │ │ ├── CustomTextInput │ │ │ ├── CustomTextInput.tsx │ │ │ └── CustomTextInput.test.tsx │ │ └── CustomSelect │ │ │ ├── CustomSelect.tsx │ │ │ └── CustomSelectInput.test.tsx │ ├── rootReducer.ts │ └── store.ts ├── features │ ├── toDo │ │ ├── selectors │ │ │ ├── errorMessageSelector.ts │ │ │ ├── toDoListSelector.ts │ │ │ └── activeProfileSelector.ts │ │ ├── components │ │ │ ├── ToDoItem │ │ │ │ ├── ToDoItem.module.css │ │ │ │ ├── getDeleteOnClick.ts │ │ │ │ ├── getIsCompleteOnChange.ts │ │ │ │ ├── getDescriptionOnChange.ts │ │ │ │ ├── ToDoItem.tsx │ │ │ │ ├── __snapshots__ │ │ │ │ │ └── ToDoItem.test.tsx.snap │ │ │ │ └── ToDoItem.test.tsx │ │ │ └── ToDoCard │ │ │ │ ├── getErrorCloseOnClick.ts │ │ │ │ ├── getCreateOnClick.ts │ │ │ │ ├── ToDoCard.tsx │ │ │ │ ├── ToDoCardFooter.tsx │ │ │ │ ├── ToDoCard.test.tsx │ │ │ │ └── __snapshots__ │ │ │ │ └── ToDoCard.test.tsx.snap │ │ ├── reducers │ │ │ ├── resetReducer.ts │ │ │ ├── setErrorMessageReducer.ts │ │ │ ├── deleteToDoReducer.ts │ │ │ ├── createToDoReducer.ts │ │ │ ├── deleteToDoReducer.test.ts │ │ │ ├── setErrorMessageReducer.test.ts │ │ │ ├── updateToDoReducer.ts │ │ │ ├── createToDoReducer.test.ts │ │ │ └── updateToDoReducer.test.ts │ │ ├── helpers │ │ │ └── toDoTemplate.ts │ │ └── toDoSlice.ts │ └── profile │ │ ├── selectors │ │ ├── profileTypesSelector.ts │ │ ├── profileListSelector.ts │ │ └── isActiveSelector.ts │ │ ├── components │ │ ├── ProfileItem │ │ │ ├── ProfileItem.module.css │ │ │ ├── getItemOnClick.ts │ │ │ ├── getNameOnChange.ts │ │ │ ├── getDeleteOnClick.ts │ │ │ ├── getTypeOnChange.ts │ │ │ ├── ProfileItem.tsx │ │ │ ├── ProfileItem.test.tsx │ │ │ └── __snapshots__ │ │ │ │ └── ProfileItem.test.tsx.snap │ │ └── ProfileCard │ │ │ ├── getCreateOnClick.ts │ │ │ ├── ProfileCard.tsx │ │ │ ├── ProfileCard.test.tsx │ │ │ └── __snapshots__ │ │ │ └── ProfileCard.test.tsx.snap │ │ ├── reducers │ │ ├── resetReducer.ts │ │ ├── setActiveProfileReducer.ts │ │ ├── createProfileReducer.ts │ │ ├── deleteProfileReducer.ts │ │ ├── setActiveProfileReducer.test.ts │ │ ├── updateProfileReducer.ts │ │ ├── deleteProfileReducer.test.ts │ │ ├── createProfileReducer.test.ts │ │ ├── updateProfileReducer.test.ts │ │ └── resetReducer.test.ts │ │ ├── helpers │ │ └── profileTemplate.ts │ │ └── profileSlice.ts ├── utils │ └── types.ts ├── setupTests.ts ├── index.css ├── index.tsx └── serviceWorker.ts ├── public ├── robots.txt ├── favicon.ico ├── logo192.png ├── logo512.png ├── manifest.json └── index.html ├── .prettierrc.js ├── .vscode ├── settings.json ├── extensions.json └── launch.json ├── .gitignore ├── tsconfig.json ├── .eslintrc.js ├── package.json └── README.md /.env: -------------------------------------------------------------------------------- 1 | EXTEND_ESLINT=true -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | src/serviceWorker.ts -------------------------------------------------------------------------------- /src/react-app-env.d.ts: -------------------------------------------------------------------------------- 1 | /// 2 | -------------------------------------------------------------------------------- /public/robots.txt: -------------------------------------------------------------------------------- 1 | # https://www.robotstxt.org/robotstxt.html 2 | User-agent: * 3 | Disallow: 4 | -------------------------------------------------------------------------------- /public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bkinseyx/testing-react-redux-toolkit/HEAD/public/favicon.ico -------------------------------------------------------------------------------- /public/logo192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bkinseyx/testing-react-redux-toolkit/HEAD/public/logo192.png -------------------------------------------------------------------------------- /public/logo512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bkinseyx/testing-react-redux-toolkit/HEAD/public/logo512.png -------------------------------------------------------------------------------- /src/app/components/CustomCheckbox/CustomCheckbox.module.css: -------------------------------------------------------------------------------- 1 | .checkbox { 2 | width: default; 3 | width: 2rem; 4 | height: 2rem; 5 | } 6 | -------------------------------------------------------------------------------- /.prettierrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | semi: true, 3 | trailingComma: 'all', 4 | singleQuote: true, 5 | printWidth: 80, 6 | tabWidth: 2, 7 | }; 8 | -------------------------------------------------------------------------------- /src/features/toDo/selectors/errorMessageSelector.ts: -------------------------------------------------------------------------------- 1 | import { RootState } from 'app/rootReducer'; 2 | 3 | export const errorMessageSelector = (state: RootState): string | undefined => 4 | state.toDo.errorMessage; 5 | -------------------------------------------------------------------------------- /src/utils/types.ts: -------------------------------------------------------------------------------- 1 | export type WithRequired = Omit, K> & 2 | Required>; 3 | 4 | export type WithOptional = Omit & 5 | Partial>; 6 | -------------------------------------------------------------------------------- /src/features/profile/selectors/profileTypesSelector.ts: -------------------------------------------------------------------------------- 1 | import { RootState } from 'app/rootReducer'; 2 | 3 | export const profileTypesSelector = (state: RootState): string[] => 4 | state.profile.profileTypes as string[]; 5 | -------------------------------------------------------------------------------- /src/features/toDo/components/ToDoItem/ToDoItem.module.css: -------------------------------------------------------------------------------- 1 | .toDoItem { 2 | display: flex; 3 | } 4 | 5 | .toDoItem > * { 6 | padding: 1rem; 7 | } 8 | 9 | .buttonWrapper { 10 | display: flex; 11 | align-items: flex-end; 12 | } 13 | -------------------------------------------------------------------------------- /src/features/profile/components/ProfileItem/ProfileItem.module.css: -------------------------------------------------------------------------------- 1 | .profileItem { 2 | display: flex; 3 | } 4 | 5 | .profileItem > * { 6 | padding: 1rem; 7 | } 8 | 9 | .buttonWrapper { 10 | display: flex; 11 | align-items: flex-end; 12 | } 13 | -------------------------------------------------------------------------------- /src/features/profile/selectors/profileListSelector.ts: -------------------------------------------------------------------------------- 1 | import { RootState } from 'app/rootReducer'; 2 | import { Profile } from '../profileSlice'; 3 | 4 | export const profileListSelector = (state: RootState): Profile[] => 5 | state.profile.profileList; 6 | -------------------------------------------------------------------------------- /src/features/profile/components/ProfileCard/getCreateOnClick.ts: -------------------------------------------------------------------------------- 1 | import { store } from 'app/store'; 2 | import { createProfile } from '../../profileSlice'; 3 | 4 | export const getCreateOnClick = () => (): void => { 5 | store.dispatch(createProfile()); 6 | }; 7 | -------------------------------------------------------------------------------- /src/features/toDo/components/ToDoCard/getErrorCloseOnClick.ts: -------------------------------------------------------------------------------- 1 | import { store } from 'app/store'; 2 | import { setErrorMessage } from '../../toDoSlice'; 3 | 4 | export const getErrorCloseOnClick = () => (): void => { 5 | store.dispatch(setErrorMessage()); 6 | }; 7 | -------------------------------------------------------------------------------- /src/app/components/CardFooterWrapper/CardFooterWrapper.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import styles from './CardFooterWrapper.module.css'; 3 | 4 | export const CardFooterWrapper: React.FC = ({ children }) => ( 5 | {children} 6 | ); 7 | -------------------------------------------------------------------------------- /src/features/toDo/reducers/resetReducer.ts: -------------------------------------------------------------------------------- 1 | import { PayloadAction } from '@reduxjs/toolkit'; 2 | 3 | import { ToDoState, initialState } from '../toDoSlice'; 4 | 5 | export const resetReducer = ( 6 | _state: ToDoState, 7 | _action: PayloadAction, 8 | ): ToDoState => initialState; 9 | -------------------------------------------------------------------------------- /src/setupTests.ts: -------------------------------------------------------------------------------- 1 | // jest-dom adds custom jest matchers for asserting on DOM nodes. 2 | // allows you to do things like: 3 | // expect(element).toHaveTextContent(/react/i) 4 | // learn more: https://github.com/testing-library/jest-dom 5 | import '@testing-library/jest-dom/extend-expect'; 6 | -------------------------------------------------------------------------------- /src/features/profile/components/ProfileItem/getItemOnClick.ts: -------------------------------------------------------------------------------- 1 | import { store } from 'app/store'; 2 | import { setActiveProfile } from '../../profileSlice'; 3 | 4 | export const getItemOnClick = (profileId?: number) => (): void => { 5 | store.dispatch(setActiveProfile(profileId)); 6 | }; 7 | -------------------------------------------------------------------------------- /src/features/profile/reducers/resetReducer.ts: -------------------------------------------------------------------------------- 1 | import { PayloadAction } from '@reduxjs/toolkit'; 2 | 3 | import { ProfileState, initialState } from '../profileSlice'; 4 | 5 | export const resetReducer = ( 6 | _state: ProfileState, 7 | _action: PayloadAction, 8 | ): ProfileState => initialState; 9 | -------------------------------------------------------------------------------- /src/app/components/App/App.css: -------------------------------------------------------------------------------- 1 | .App { 2 | padding: 2rem; 3 | display: flex; 4 | flex-wrap: wrap; 5 | margin-right: -2rem; 6 | } 7 | 8 | .App > * { 9 | width: 50rem; 10 | margin-right: 2rem; 11 | margin-bottom: 2rem; 12 | } 13 | 14 | h5 { 15 | margin-bottom: 0 !important; 16 | } 17 | -------------------------------------------------------------------------------- /src/features/toDo/selectors/toDoListSelector.ts: -------------------------------------------------------------------------------- 1 | import { RootState } from 'app/rootReducer'; 2 | import { ToDo } from '../toDoSlice'; 3 | 4 | export const toDoListSelector = (state: RootState): ToDo[] => 5 | state.toDo.toDoList.filter( 6 | (toDo) => toDo.profileId === state.profile.activeProfileId, 7 | ); 8 | -------------------------------------------------------------------------------- /src/features/toDo/reducers/setErrorMessageReducer.ts: -------------------------------------------------------------------------------- 1 | import { PayloadAction } from '@reduxjs/toolkit'; 2 | import { ToDoState } from '../toDoSlice'; 3 | 4 | export const setErrorMessageReducer = ( 5 | state: ToDoState, 6 | action: PayloadAction, 7 | ): void => { 8 | state.errorMessage = action.payload; 9 | }; 10 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "editor.formatOnSave": true, 3 | "editor.tabSize": 2, 4 | "prettier.singleQuote": true, 5 | "files.eol": "\n", 6 | "typescript.tsserver.experimental.enableProjectDiagnostics": true, 7 | "codemetrics.nodeconfiguration.JsxSelfClosingElement": 0.5, 8 | "codemetrics.nodeconfiguration.JsxElement": 0.5 9 | } 10 | -------------------------------------------------------------------------------- /src/features/toDo/components/ToDoItem/getDeleteOnClick.ts: -------------------------------------------------------------------------------- 1 | import { deleteToDo } from '../../toDoSlice'; 2 | import { store } from 'app/store'; 3 | 4 | export const getDeleteOnClick = (toDoId?: number) => (): void => { 5 | /* istanbul ignore next */ 6 | if (!toDoId) { 7 | return; 8 | } 9 | store.dispatch(deleteToDo(toDoId)); 10 | }; 11 | -------------------------------------------------------------------------------- /src/features/profile/reducers/setActiveProfileReducer.ts: -------------------------------------------------------------------------------- 1 | import { PayloadAction } from '@reduxjs/toolkit'; 2 | import { ProfileState } from '../profileSlice'; 3 | 4 | export const setActiveProfileReducer = ( 5 | state: ProfileState, 6 | action: PayloadAction, 7 | ): void => { 8 | state.activeProfileId = action.payload; 9 | }; 10 | -------------------------------------------------------------------------------- /src/features/toDo/selectors/activeProfileSelector.ts: -------------------------------------------------------------------------------- 1 | import { RootState } from 'app/rootReducer'; 2 | import { Profile } from 'features/profile/profileSlice'; 3 | 4 | export const activeProfileSelector = (state: RootState): Profile | undefined => 5 | state.profile.profileList.find( 6 | (profile) => profile.profileId === state.profile.activeProfileId, 7 | ); 8 | -------------------------------------------------------------------------------- /.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | "recommendations": [ 3 | "msjsdiag.debugger-for-chrome", 4 | "clinyong.vscode-css-modules", 5 | "kisstkondoros.vscode-codemetrics", 6 | "mikestead.dotenv", 7 | "dbaeumer.vscode-eslint", 8 | "orta.vscode-jest", 9 | "esbenp.prettier-vscode", 10 | "visualstudioexptteam.vscodeintellicode", 11 | "tlent.jest-snapshot-language-support" 12 | ] 13 | } 14 | -------------------------------------------------------------------------------- /src/features/toDo/components/ToDoCard/getCreateOnClick.ts: -------------------------------------------------------------------------------- 1 | import { store } from 'app/store'; 2 | import { createToDo, setErrorMessage } from '../../toDoSlice'; 3 | 4 | export const getCreateOnClick = (profileId?: number) => (): void => { 5 | if (!profileId) { 6 | store.dispatch(setErrorMessage('Must select a profile first.')); 7 | return; 8 | } 9 | store.dispatch(createToDo(profileId)); 10 | }; 11 | -------------------------------------------------------------------------------- /src/app/rootReducer.ts: -------------------------------------------------------------------------------- 1 | import { combineReducers } from '@reduxjs/toolkit'; 2 | import profileReducer from '../features/profile/profileSlice'; 3 | import toDoReducer from '../features/toDo/toDoSlice'; 4 | 5 | const rootReducer = combineReducers({ 6 | profile: profileReducer, 7 | toDo: toDoReducer, 8 | }); 9 | 10 | export type RootState = ReturnType; 11 | 12 | export default rootReducer; 13 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # production 12 | /build 13 | 14 | # misc 15 | .DS_Store 16 | .env.local 17 | .env.development.local 18 | .env.test.local 19 | .env.production.local 20 | 21 | npm-debug.log* 22 | yarn-debug.log* 23 | yarn-error.log* 24 | -------------------------------------------------------------------------------- /src/features/profile/reducers/createProfileReducer.ts: -------------------------------------------------------------------------------- 1 | import { ProfileState } from '../profileSlice'; 2 | import { emptyProfile } from '../helpers/profileTemplate'; 3 | 4 | export const createProfileReducer = (state: ProfileState): void => { 5 | const profileId = ++state.maxProfileId; 6 | state.profileList.push({ 7 | ...emptyProfile, 8 | profileId, 9 | }); 10 | state.activeProfileId = profileId; 11 | }; 12 | -------------------------------------------------------------------------------- /src/features/toDo/reducers/deleteToDoReducer.ts: -------------------------------------------------------------------------------- 1 | import { PayloadAction } from '@reduxjs/toolkit'; 2 | 3 | import { ToDoState } from '../toDoSlice'; 4 | 5 | export const deleteToDoReducer = ( 6 | state: ToDoState, 7 | action: PayloadAction, 8 | ): void => { 9 | const index = state.toDoList.findIndex( 10 | (toDo) => toDo.toDoId === action.payload, 11 | ); 12 | state.toDoList.splice(index, 1); 13 | }; 14 | -------------------------------------------------------------------------------- /src/index.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin: 0; 3 | font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 4 | 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', 5 | sans-serif; 6 | -webkit-font-smoothing: antialiased; 7 | -moz-osx-font-smoothing: grayscale; 8 | } 9 | 10 | code { 11 | font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', 12 | monospace; 13 | } 14 | -------------------------------------------------------------------------------- /src/features/profile/components/ProfileItem/getNameOnChange.ts: -------------------------------------------------------------------------------- 1 | import { store } from 'app/store'; 2 | import { updateProfile } from '../../profileSlice'; 3 | 4 | export const getNameOnChange = (profileId?: number) => (name: string): void => { 5 | /* istanbul ignore next */ 6 | if (!profileId) { 7 | return; 8 | } 9 | store.dispatch( 10 | updateProfile({ 11 | profileId, 12 | name, 13 | }), 14 | ); 15 | }; 16 | -------------------------------------------------------------------------------- /src/features/toDo/components/ToDoItem/getIsCompleteOnChange.ts: -------------------------------------------------------------------------------- 1 | import { updateToDo } from '../../toDoSlice'; 2 | import { store } from 'app/store'; 3 | 4 | export const getIsCompleteOnChange = (toDoId?: number) => ( 5 | isComplete: boolean, 6 | ): void => { 7 | /* istanbul ignore next */ 8 | if (!toDoId) { 9 | return; 10 | } 11 | store.dispatch( 12 | updateToDo({ 13 | toDoId, 14 | isComplete, 15 | }), 16 | ); 17 | }; 18 | -------------------------------------------------------------------------------- /src/features/toDo/helpers/toDoTemplate.ts: -------------------------------------------------------------------------------- 1 | import { ToDo } from '../toDoSlice'; 2 | import { WithRequired, WithOptional } from 'utils/types'; 3 | 4 | type ToDoTemplateFields = 'isComplete'; 5 | 6 | export type EmptyToDo = WithRequired; 7 | 8 | export const emptyToDo: EmptyToDo = { 9 | isComplete: false, 10 | }; 11 | 12 | export type PartialToDo = WithOptional< 13 | Omit, 14 | ToDoTemplateFields 15 | >; 16 | -------------------------------------------------------------------------------- /src/features/toDo/components/ToDoItem/getDescriptionOnChange.ts: -------------------------------------------------------------------------------- 1 | import { updateToDo } from '../../toDoSlice'; 2 | import { store } from 'app/store'; 3 | 4 | export const getDescriptionOnChange = (toDoId?: number) => ( 5 | description: string, 6 | ): void => { 7 | /* istanbul ignore next */ 8 | if (!toDoId) { 9 | return; 10 | } 11 | store.dispatch( 12 | updateToDo({ 13 | toDoId, 14 | description, 15 | }), 16 | ); 17 | }; 18 | -------------------------------------------------------------------------------- /src/features/profile/selectors/isActiveSelector.ts: -------------------------------------------------------------------------------- 1 | import { RootState } from 'app/rootReducer'; 2 | import { Profile } from '../profileSlice'; 3 | import { WithRequired } from 'utils/types'; 4 | import { ProfileTemplateFields } from '../helpers/profileTemplate'; 5 | 6 | export const getIsActiveSelector = ( 7 | profile: WithRequired, 8 | ) => (state: RootState): boolean => 9 | state.profile.activeProfileId === profile.profileId; 10 | -------------------------------------------------------------------------------- /src/features/profile/components/ProfileItem/getDeleteOnClick.ts: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { store } from 'app/store'; 3 | import { deleteProfile } from '../../profileSlice'; 4 | 5 | export const getDeleteOnClick = (profileId?: number) => ( 6 | event: React.MouseEvent, 7 | ): void => { 8 | /* istanbul ignore next */ 9 | if (!profileId) { 10 | return; 11 | } 12 | store.dispatch(deleteProfile(profileId)); 13 | event.stopPropagation(); 14 | }; 15 | -------------------------------------------------------------------------------- /src/features/toDo/reducers/createToDoReducer.ts: -------------------------------------------------------------------------------- 1 | import { PayloadAction } from '@reduxjs/toolkit'; 2 | import { ToDoState } from '../toDoSlice'; 3 | import { emptyToDo } from '../helpers/toDoTemplate'; 4 | 5 | export const createToDoReducer = ( 6 | state: ToDoState, 7 | action: PayloadAction, 8 | ): void => { 9 | const toDoId = ++state.maxToDoId; 10 | state.toDoList.push({ 11 | ...emptyToDo, 12 | profileId: action.payload, 13 | toDoId, 14 | }); 15 | }; 16 | -------------------------------------------------------------------------------- /src/features/profile/components/ProfileItem/getTypeOnChange.ts: -------------------------------------------------------------------------------- 1 | import { store } from 'app/store'; 2 | import { updateProfile, ProfileType } from '../../profileSlice'; 3 | 4 | export const getTypeOnChange = (profileId?: number) => ( 5 | value: string, 6 | ): void => { 7 | /* istanbul ignore next */ 8 | if (!profileId) { 9 | return; 10 | } 11 | store.dispatch( 12 | updateProfile({ 13 | profileId, 14 | profileType: value as ProfileType, 15 | }), 16 | ); 17 | }; 18 | -------------------------------------------------------------------------------- /src/app/components/CardFooterWrapper/CardFooterWrapper.module.css: -------------------------------------------------------------------------------- 1 | .wrapper { 2 | display: flex; 3 | margin-right: -10px; 4 | } 5 | 6 | .wrapper > * { 7 | margin: 0; 8 | margin-right: 10px; 9 | padding: 0.5rem 1rem; 10 | } 11 | 12 | .wrapper > *:nth-child(2) { 13 | flex-grow: 1; 14 | } 15 | 16 | .wrapper > *:nth-child(2) button { 17 | padding: 0; 18 | height: 100%; 19 | display: flex; 20 | flex-direction: column; 21 | justify-content: center; 22 | margin-right: 10px; 23 | } 24 | -------------------------------------------------------------------------------- /src/app/components/App/App.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import 'bootstrap/dist/css/bootstrap.min.css'; 3 | 4 | import './App.css'; 5 | import { ProfileCard } from 'features/profile/components/ProfileCard/ProfileCard'; 6 | import { ToDoCard } from 'features/toDo/components/ToDoCard/ToDoCard'; 7 | 8 | const App: React.FC = () => { 9 | return ( 10 | 11 | 12 | 13 | 14 | ); 15 | }; 16 | 17 | export default App; 18 | -------------------------------------------------------------------------------- /src/features/toDo/reducers/deleteToDoReducer.test.ts: -------------------------------------------------------------------------------- 1 | import { store } from 'app/store'; 2 | import { deleteToDo } from '../toDoSlice'; 3 | 4 | test('deleteToDo test', () => { 5 | let state = store.getState().toDo; 6 | expect(state.toDoList).toHaveLength(3); 7 | 8 | store.dispatch(deleteToDo(1)); 9 | state = store.getState().toDo; 10 | expect(state.toDoList).toHaveLength(2); 11 | 12 | store.dispatch(deleteToDo(2)); 13 | state = store.getState().toDo; 14 | expect(state.toDoList).toHaveLength(1); 15 | }); 16 | -------------------------------------------------------------------------------- /src/features/profile/helpers/profileTemplate.ts: -------------------------------------------------------------------------------- 1 | import { Profile } from '../profileSlice'; 2 | import { WithRequired, WithOptional } from 'utils/types'; 3 | 4 | export type ProfileTemplateFields = 'showToDoList' | 'profileType'; 5 | 6 | export type EmptyProfile = WithRequired; 7 | 8 | export const emptyProfile: EmptyProfile = { 9 | profileType: 'guest', 10 | showToDoList: false, 11 | }; 12 | 13 | export type PartialProfile = WithOptional< 14 | Omit, 15 | ProfileTemplateFields 16 | >; 17 | -------------------------------------------------------------------------------- /src/features/profile/reducers/deleteProfileReducer.ts: -------------------------------------------------------------------------------- 1 | import { PayloadAction } from '@reduxjs/toolkit'; 2 | 3 | import { ProfileState } from '../profileSlice'; 4 | 5 | export const deleteProfileReducer = ( 6 | state: ProfileState, 7 | action: PayloadAction, 8 | ): void => { 9 | const index = state.profileList.findIndex( 10 | (profile) => profile.profileId === action.payload, 11 | ); 12 | state.profileList.splice(index, 1); 13 | if (state.activeProfileId === action.payload) { 14 | state.activeProfileId = undefined; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /src/features/profile/reducers/setActiveProfileReducer.test.ts: -------------------------------------------------------------------------------- 1 | import { store } from 'app/store'; 2 | import { setActiveProfile } from '../profileSlice'; 3 | 4 | test('setActiveProfile test', () => { 5 | let state = store.getState().profile; 6 | expect(state.activeProfileId).toBeUndefined(); 7 | 8 | store.dispatch(setActiveProfile(2)); 9 | state = store.getState().profile; 10 | expect(state.activeProfileId).toBe(2); 11 | 12 | store.dispatch(setActiveProfile(1)); 13 | state = store.getState().profile; 14 | expect(state.activeProfileId).toBe(1); 15 | }); 16 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es5", 4 | "lib": ["dom", "dom.iterable", "esnext"], 5 | "allowJs": true, 6 | "skipLibCheck": true, 7 | "esModuleInterop": true, 8 | "allowSyntheticDefaultImports": true, 9 | "strict": true, 10 | "forceConsistentCasingInFileNames": true, 11 | "module": "esnext", 12 | "moduleResolution": "node", 13 | "resolveJsonModule": true, 14 | "isolatedModules": true, 15 | "noEmit": true, 16 | "jsx": "react", 17 | "baseUrl": "src" 18 | }, 19 | "include": ["src"] 20 | } 21 | -------------------------------------------------------------------------------- /src/features/toDo/reducers/setErrorMessageReducer.test.ts: -------------------------------------------------------------------------------- 1 | import { store } from 'app/store'; 2 | import { setErrorMessage } from '../toDoSlice'; 3 | 4 | test('deleteToDo test', () => { 5 | let state = store.getState().toDo; 6 | expect(state.errorMessage).toBeUndefined(); 7 | 8 | store.dispatch(setErrorMessage('this is the error message')); 9 | state = store.getState().toDo; 10 | expect(state.errorMessage).toBe('this is the error message'); 11 | 12 | store.dispatch(setErrorMessage()); 13 | state = store.getState().toDo; 14 | expect(state.errorMessage).toBeUndefined(); 15 | }); 16 | -------------------------------------------------------------------------------- /src/features/toDo/reducers/updateToDoReducer.ts: -------------------------------------------------------------------------------- 1 | import { PayloadAction } from '@reduxjs/toolkit'; 2 | 3 | import { ToDoState, ToDo } from '../toDoSlice'; 4 | import { WithRequired } from 'utils/types'; 5 | 6 | export const updateToDoReducer = ( 7 | state: ToDoState, 8 | action: PayloadAction>, 9 | ): void => { 10 | const toDo = state.toDoList.find( 11 | (existingToDo) => existingToDo.toDoId === action.payload.toDoId, 12 | ); 13 | /* istanbul ignore next */ 14 | if (!toDo) { 15 | return; 16 | } 17 | Object.assign(toDo, action.payload); 18 | }; 19 | -------------------------------------------------------------------------------- /public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "React App", 3 | "name": "Create React App Sample", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "64x64 32x32 24x24 16x16", 8 | "type": "image/x-icon" 9 | }, 10 | { 11 | "src": "logo192.png", 12 | "type": "image/png", 13 | "sizes": "192x192" 14 | }, 15 | { 16 | "src": "logo512.png", 17 | "type": "image/png", 18 | "sizes": "512x512" 19 | } 20 | ], 21 | "start_url": ".", 22 | "display": "standalone", 23 | "theme_color": "#000000", 24 | "background_color": "#ffffff" 25 | } 26 | -------------------------------------------------------------------------------- /src/features/profile/reducers/updateProfileReducer.ts: -------------------------------------------------------------------------------- 1 | import { PayloadAction } from '@reduxjs/toolkit'; 2 | 3 | import { ProfileState, Profile } from '../profileSlice'; 4 | import { WithRequired } from 'utils/types'; 5 | 6 | export const updateProfileReducer = ( 7 | state: ProfileState, 8 | action: PayloadAction>, 9 | ): void => { 10 | const profile = state.profileList.find( 11 | (existingProfile) => existingProfile.profileId === action.payload.profileId, 12 | ); 13 | /* istanbul ignore next */ 14 | if (!profile) { 15 | return; 16 | } 17 | Object.assign(profile, action.payload); 18 | }; 19 | -------------------------------------------------------------------------------- /src/app/store.ts: -------------------------------------------------------------------------------- 1 | import { configureStore, ThunkAction, Action } from '@reduxjs/toolkit'; 2 | 3 | import rootReducer from './rootReducer'; 4 | 5 | export const store = configureStore({ 6 | reducer: rootReducer, 7 | }); 8 | 9 | /* istanbul ignore next */ 10 | if (process.env.NODE_ENV === 'development' && module.hot) { 11 | module.hot.accept('./rootReducer', async () => { 12 | const newRootReducer = (await import('./rootReducer')).default; 13 | store.replaceReducer(newRootReducer); 14 | }); 15 | } 16 | 17 | export type RootState = ReturnType; 18 | export type AppThunk = ThunkAction< 19 | ReturnType, 20 | RootState, 21 | unknown, 22 | Action 23 | >; 24 | -------------------------------------------------------------------------------- /src/features/profile/reducers/deleteProfileReducer.test.ts: -------------------------------------------------------------------------------- 1 | import { store } from 'app/store'; 2 | import { deleteProfile, setActiveProfile } from '../profileSlice'; 3 | 4 | test('deleteProfile test', () => { 5 | let state = store.getState().profile; 6 | expect(state.profileList).toHaveLength(2); 7 | 8 | store.dispatch(deleteProfile(1)); 9 | state = store.getState().profile; 10 | expect(state.profileList).toHaveLength(1); 11 | expect(state.activeProfileId).toBeUndefined(); 12 | 13 | store.dispatch(setActiveProfile(2)); 14 | state = store.getState().profile; 15 | expect(state.activeProfileId).toBe(2); 16 | 17 | store.dispatch(deleteProfile(2)); 18 | state = store.getState().profile; 19 | expect(state.activeProfileId).toBeUndefined(); 20 | }); 21 | -------------------------------------------------------------------------------- /src/app/components/CustomTextInput/CustomTextInput.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | 3 | interface CustomTextInputProps { 4 | onChange: (value: string) => void; 5 | value?: string; 6 | label: string; 7 | idPrefix: string; 8 | autoFocus?: boolean; 9 | } 10 | 11 | export const CustomTextInput: React.FC = ({ 12 | value, 13 | onChange, 14 | label, 15 | idPrefix, 16 | autoFocus, 17 | }) => { 18 | const inputId = `${idPrefix}-input`; 19 | 20 | return ( 21 | 22 | {label} 23 | onChange(event.target.value)} 29 | autoFocus={autoFocus} 30 | /> 31 | 32 | ); 33 | }; 34 | -------------------------------------------------------------------------------- /src/app/components/CustomSelect/CustomSelect.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | 3 | interface CustomSelectProps { 4 | onChange: (value: string) => void; 5 | options: string[]; 6 | value: string; 7 | label: string; 8 | idPrefix: string; 9 | } 10 | 11 | export const CustomSelect: React.FC = ({ 12 | options, 13 | value, 14 | onChange, 15 | label, 16 | idPrefix, 17 | }) => { 18 | const selectId = `${idPrefix}-select`; 19 | return ( 20 | 21 | {label} 22 | onChange(event?.target.value)} 27 | > 28 | {options.map((option) => ( 29 | {option} 30 | ))} 31 | 32 | 33 | ); 34 | }; 35 | -------------------------------------------------------------------------------- /src/features/toDo/reducers/createToDoReducer.test.ts: -------------------------------------------------------------------------------- 1 | import { store } from 'app/store'; 2 | import { createToDo } from '../toDoSlice'; 3 | import { emptyToDo } from '../helpers/toDoTemplate'; 4 | 5 | test('createToDo test', () => { 6 | let state = store.getState().toDo; 7 | expect(state.toDoList).toHaveLength(3); 8 | expect(state.maxToDoId).toBe(3); 9 | 10 | const profileId = 1; 11 | store.dispatch(createToDo(profileId)); 12 | state = store.getState().toDo; 13 | expect(state.toDoList).toHaveLength(4); 14 | expect(state.maxToDoId).toBe(4); 15 | const newToDo = state.toDoList[3]; 16 | expect(newToDo).toMatchInlineSnapshot( 17 | newToDo, 18 | ` 19 | Object { 20 | "isComplete": false, 21 | "profileId": 1, 22 | "toDoId": 4, 23 | } 24 | `, 25 | ); 26 | expect(newToDo).toEqual({ 27 | ...emptyToDo, 28 | profileId: 1, 29 | toDoId: 4, 30 | }); 31 | }); 32 | -------------------------------------------------------------------------------- /src/app/components/CustomCheckbox/CustomCheckbox.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | 3 | import styles from './CustomCheckbox.module.css'; 4 | 5 | interface CustomCheckboxProps { 6 | onChange: (value: boolean) => void; 7 | checked?: boolean; 8 | label: string; 9 | idPrefix: string; 10 | autoFocus?: boolean; 11 | } 12 | 13 | export const CustomCheckbox: React.FC = ({ 14 | checked, 15 | onChange, 16 | label, 17 | idPrefix, 18 | autoFocus, 19 | }) => { 20 | const inputId = `${idPrefix}-input`; 21 | 22 | return ( 23 | 24 | {label} 25 | onChange(event.target.checked)} 31 | autoFocus={autoFocus} 32 | /> 33 | 34 | ); 35 | }; 36 | -------------------------------------------------------------------------------- /src/features/profile/reducers/createProfileReducer.test.ts: -------------------------------------------------------------------------------- 1 | import { store } from 'app/store'; 2 | import { createProfile } from '../profileSlice'; 3 | import { emptyProfile } from '../helpers/profileTemplate'; 4 | 5 | test('createProfile test', () => { 6 | let state = store.getState().profile; 7 | expect(state.profileList).toHaveLength(2); 8 | expect(state.maxProfileId).toBe(2); 9 | 10 | store.dispatch(createProfile()); 11 | state = store.getState().profile; 12 | expect(state.profileList).toHaveLength(3); 13 | expect(state.maxProfileId).toBe(3); 14 | const newProfile = state.profileList[2]; 15 | expect(newProfile).toMatchInlineSnapshot( 16 | newProfile, 17 | ` 18 | Object { 19 | "profileId": 3, 20 | "profileType": "guest", 21 | "showToDoList": false, 22 | } 23 | `, 24 | ); 25 | expect(newProfile).toEqual({ 26 | ...emptyProfile, 27 | profileId: 3, 28 | }); 29 | }); 30 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "name": "Debug tests single run", 9 | "type": "node", 10 | "request": "launch", 11 | "env": { "CI": "true" }, 12 | "runtimeExecutable": "${workspaceRoot}/node_modules/.bin/react-scripts", 13 | "args": ["test", "--runInBand", "--no-cache"], 14 | "cwd": "${workspaceRoot}", 15 | "protocol": "inspector", 16 | "console": "integratedTerminal", 17 | "internalConsoleOptions": "neverOpen" 18 | }, 19 | { 20 | "type": "chrome", 21 | "request": "launch", 22 | "name": "Launch Chrome against localhost", 23 | "url": "http://localhost:3000", 24 | "webRoot": "${workspaceFolder}" 25 | } 26 | ] 27 | } 28 | -------------------------------------------------------------------------------- /src/index.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import './index.css'; 4 | import { Provider } from 'react-redux'; 5 | 6 | import { store } from './app/store'; 7 | import * as serviceWorker from './serviceWorker'; 8 | 9 | const render = async (): Promise => { 10 | const App = (await import('./app/components/App/App')).default; 11 | 12 | ReactDOM.render( 13 | 14 | 15 | 16 | 17 | , 18 | document.getElementById('root'), 19 | ); 20 | }; 21 | 22 | render(); 23 | 24 | if (process.env.NODE_ENV === 'development' && module.hot) { 25 | module.hot.accept('./app/components/App/App', render); 26 | } 27 | 28 | // If you want your app to work offline and load faster, you can change 29 | // unregister() to register() below. Note this comes with some pitfalls. 30 | // Learn more about service workers: https://bit.ly/CRA-PWA 31 | serviceWorker.unregister(); 32 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | parser: '@typescript-eslint/parser', 3 | extends: [ 4 | 'plugin:sonarjs/recommended', 5 | 'plugin:react/recommended', 6 | 'plugin:@typescript-eslint/recommended', 7 | 'prettier/@typescript-eslint', 8 | 'plugin:prettier/recommended', 9 | ], 10 | parserOptions: { 11 | ecmaVersion: 2018, 12 | sourceType: 'module', 13 | ecmaFeatures: { 14 | jsx: true, 15 | }, 16 | }, 17 | settings: { 18 | react: { 19 | version: 'detect', 20 | }, 21 | }, 22 | rules: { 23 | 'react/prop-types': ['off'], 24 | 'sonarjs/cognitive-complexity': ['error', 8], 25 | 'max-lines-per-function': ['error', 60], 26 | 'prettier/prettier': ['off'], 27 | '@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_' }], 28 | 'no-shadow': ['error', { builtinGlobals: true, hoist: 'all' }], 29 | eqeqeq: ['error', 'always'], 30 | 'func-style': ['error', 'expression'], 31 | 'react/prefer-stateless-function': ['error'], 32 | }, 33 | }; 34 | -------------------------------------------------------------------------------- /src/features/profile/reducers/updateProfileReducer.test.ts: -------------------------------------------------------------------------------- 1 | import { store } from 'app/store'; 2 | import { updateProfile } from '../profileSlice'; 3 | 4 | test('updateProfile test', () => { 5 | let state = store.getState().profile; 6 | expect(state.activeProfileId).toBeUndefined(); 7 | let profile = state.profileList.find((p) => p.profileId === 1); 8 | expect(profile?.name).toBe('Ben'); 9 | expect(profile?.profileType).toBe('admin'); 10 | store.dispatch(updateProfile({ profileId: 1, name: 'John' })); 11 | state = store.getState().profile; 12 | profile = state.profileList.find((p) => p.profileId === 1); 13 | expect(profile?.name).toBe('John'); 14 | store.dispatch(updateProfile({ profileId: 1, profileType: 'user' })); 15 | state = store.getState().profile; 16 | profile = state.profileList.find((p) => p.profileId === 1); 17 | expect(profile?.profileType).toBe('user'); 18 | expect(profile).toMatchInlineSnapshot(` 19 | Object { 20 | "name": "John", 21 | "profileId": 1, 22 | "profileType": "user", 23 | "showToDoList": true, 24 | } 25 | `); 26 | }); 27 | -------------------------------------------------------------------------------- /src/features/toDo/components/ToDoCard/ToDoCard.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { useSelector } from 'react-redux'; 3 | 4 | import { ToDoItem } from '../ToDoItem/ToDoItem'; 5 | import { toDoListSelector } from '../../selectors/toDoListSelector'; 6 | import { activeProfileSelector } from '../../selectors/activeProfileSelector'; 7 | import { ToDoCardFooter } from './ToDoCardFooter'; 8 | 9 | export const ToDoCard: React.FC = () => { 10 | const toDoList = useSelector(toDoListSelector); 11 | const activeProfile = useSelector(activeProfileSelector); 12 | return ( 13 | 14 | 15 | 16 | ToDos {activeProfile?.name && `for ${activeProfile?.name}`} 17 | 18 | 19 | 20 | 21 | {toDoList.map((toDo) => ( 22 | 23 | ))} 24 | 25 | 26 | 27 | 28 | ); 29 | }; 30 | -------------------------------------------------------------------------------- /src/features/profile/reducers/resetReducer.test.ts: -------------------------------------------------------------------------------- 1 | import { store } from 'app/store'; 2 | import { deleteProfile, reset, initialState } from '../profileSlice'; 3 | 4 | test('reset test', () => { 5 | const unchangedState = store.getState().profile; 6 | store.dispatch(deleteProfile(1)); 7 | store.dispatch(deleteProfile(2)); 8 | const changedState = store.getState().profile; 9 | expect(changedState).not.toEqual(unchangedState); 10 | store.dispatch(reset()); 11 | const resetState = store.getState().profile; 12 | expect(resetState).toEqual(unchangedState); 13 | expect(resetState).toEqual(initialState); 14 | expect(resetState).toMatchInlineSnapshot(` 15 | Object { 16 | "maxProfileId": 2, 17 | "profileList": Array [ 18 | Object { 19 | "name": "Ben", 20 | "profileId": 1, 21 | "profileType": "admin", 22 | "showToDoList": true, 23 | }, 24 | Object { 25 | "name": "Sue", 26 | "profileId": 2, 27 | "profileType": "user", 28 | "showToDoList": false, 29 | }, 30 | ], 31 | "profileTypes": Array [ 32 | "guest", 33 | "user", 34 | "admin", 35 | ], 36 | } 37 | `); 38 | }); 39 | -------------------------------------------------------------------------------- /src/features/profile/components/ProfileCard/ProfileCard.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { useSelector } from 'react-redux'; 3 | 4 | import { ProfileItem } from '../ProfileItem/ProfileItem'; 5 | import { profileListSelector } from '../../selectors/profileListSelector'; 6 | import { getCreateOnClick } from './getCreateOnClick'; 7 | import { CardFooterWrapper } from 'app/components/CardFooterWrapper/CardFooterWrapper'; 8 | 9 | export const ProfileCard: React.FC = () => { 10 | const profileList = useSelector(profileListSelector); 11 | return ( 12 | 13 | 14 | Profiles 15 | 16 | 17 | 18 | {profileList.map((profile) => ( 19 | 23 | ))} 24 | 25 | 26 | 27 | 28 | 29 | Create New Profile 30 | 31 | 32 | 33 | 34 | ); 35 | }; 36 | -------------------------------------------------------------------------------- /src/features/toDo/components/ToDoCard/ToDoCardFooter.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { useSelector } from 'react-redux'; 3 | import { Alert } from 'react-bootstrap'; 4 | import classNames from 'classnames'; 5 | 6 | import { CardFooterWrapper } from 'app/components/CardFooterWrapper/CardFooterWrapper'; 7 | import { getCreateOnClick } from './getCreateOnClick'; 8 | import { getErrorCloseOnClick } from './getErrorCloseOnClick'; 9 | import { activeProfileSelector } from '../../selectors/activeProfileSelector'; 10 | import { errorMessageSelector } from 'features/toDo/selectors/errorMessageSelector'; 11 | 12 | export const ToDoCardFooter: React.FC = () => { 13 | const activeProfile = useSelector(activeProfileSelector); 14 | const errorMessage = useSelector(errorMessageSelector); 15 | return ( 16 | 17 | 18 | 24 | Create New ToDo 25 | 26 | {errorMessage && ( 27 | 28 | {errorMessage} 29 | 30 | )} 31 | 32 | 33 | ); 34 | }; 35 | -------------------------------------------------------------------------------- /src/app/components/CustomTextInput/CustomTextInput.test.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { render, screen, fireEvent } from '@testing-library/react'; 3 | 4 | import { CustomTextInput } from './CustomTextInput'; 5 | 6 | const changeHandler = jest.fn(); 7 | 8 | test('renders the text input', () => { 9 | const { rerender, asFragment } = render( 10 | , 16 | ); 17 | expect(asFragment()).toMatchInlineSnapshot(` 18 | 19 | 20 | 23 | My Label 24 | 25 | 31 | 32 | 33 | `); 34 | const textInput = screen.getByLabelText('My Label'); 35 | expect(textInput).toHaveValue('original value'); 36 | fireEvent.change(textInput, { target: { value: 'new value' } }); 37 | expect(changeHandler).toHaveBeenCalledWith('new value'); 38 | rerender( 39 | , 45 | ); 46 | expect(textInput).toHaveValue('new value'); 47 | }); 48 | -------------------------------------------------------------------------------- /src/features/toDo/components/ToDoItem/ToDoItem.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import styles from './ToDoItem.module.css'; 3 | 4 | import { ToDo } from '../../toDoSlice'; 5 | import { CustomTextInput } from 'app/components/CustomTextInput/CustomTextInput'; 6 | import { emptyToDo } from '../../helpers/toDoTemplate'; 7 | import { getDescriptionOnChange } from './getDescriptionOnChange'; 8 | import { getDeleteOnClick } from './getDeleteOnClick'; 9 | import { getIsCompleteOnChange } from './getIsCompleteOnChange'; 10 | import { CustomCheckbox } from 'app/components/CustomCheckbox/CustomCheckbox'; 11 | 12 | interface ToDoProps { 13 | toDo: ToDo; 14 | } 15 | 16 | export const ToDoItem: React.FC = ({ toDo = emptyToDo }) => { 17 | return ( 18 | 19 | 25 | 31 | 32 | 36 | Delete 37 | 38 | 39 | 40 | ); 41 | }; 42 | -------------------------------------------------------------------------------- /src/features/toDo/reducers/updateToDoReducer.test.ts: -------------------------------------------------------------------------------- 1 | import { store } from 'app/store'; 2 | import { updateToDo } from '../toDoSlice'; 3 | 4 | test('updateToDo test', () => { 5 | // this will set a breakpoint when you debug this test in your browser 6 | debugger; 7 | let state = store.getState().toDo; 8 | const originalToDo = state.toDoList.find((p) => p.toDoId === 1); 9 | expect(originalToDo?.isComplete).toBeTruthy(); 10 | expect(originalToDo?.description).toBe('eat tacos'); 11 | 12 | store.dispatch(updateToDo({ toDoId: 1, isComplete: false })); 13 | state = store.getState().toDo; 14 | let changedToDo = state.toDoList.find((p) => p.toDoId === 1); 15 | expect(changedToDo?.isComplete).toBeFalsy(); 16 | 17 | store.dispatch(updateToDo({ toDoId: 1, description: 'be merry' })); 18 | state = store.getState().toDo; 19 | changedToDo = state.toDoList.find((p) => p.toDoId === 1); 20 | expect(changedToDo?.description).toBe('be merry'); 21 | 22 | store.dispatch( 23 | updateToDo({ toDoId: 1, description: 'eat tacos', isComplete: true }), 24 | ); 25 | state = store.getState().toDo; 26 | const backToOriginalToDo = state.toDoList.find((p) => p.toDoId === 1); 27 | 28 | // snapshots can be objects 29 | expect(backToOriginalToDo).toMatchInlineSnapshot(` 30 | Object { 31 | "description": "eat tacos", 32 | "isComplete": true, 33 | "profileId": 1, 34 | "toDoId": 1, 35 | } 36 | `); 37 | 38 | // deep object equality 39 | expect(backToOriginalToDo).toEqual(originalToDo); 40 | }); 41 | -------------------------------------------------------------------------------- /src/features/toDo/toDoSlice.ts: -------------------------------------------------------------------------------- 1 | import { createSlice } from '@reduxjs/toolkit'; 2 | 3 | import { createToDoReducer } from './reducers/createToDoReducer'; 4 | import { deleteToDoReducer } from './reducers/deleteToDoReducer'; 5 | import { updateToDoReducer } from './reducers/updateToDoReducer'; 6 | import { resetReducer } from './reducers/resetReducer'; 7 | import { setErrorMessageReducer } from './reducers/setErrorMessageReducer'; 8 | 9 | export interface ToDo { 10 | toDoId: number; 11 | description?: string; 12 | profileId: number; 13 | isComplete: boolean; 14 | } 15 | 16 | export interface ToDoState { 17 | toDoList: ToDo[]; 18 | maxToDoId: number; 19 | errorMessage?: string; 20 | } 21 | 22 | export const initialState: ToDoState = { 23 | toDoList: [ 24 | { toDoId: 1, profileId: 1, description: 'eat tacos', isComplete: true }, 25 | { toDoId: 2, profileId: 1, description: 'drink milk', isComplete: false }, 26 | { 27 | toDoId: 3, 28 | profileId: 1, 29 | description: 'walk and chew gum', 30 | isComplete: false, 31 | }, 32 | ], 33 | maxToDoId: 3, 34 | }; 35 | 36 | export const toDoSlice = createSlice({ 37 | name: 'toDo', 38 | initialState, 39 | reducers: { 40 | createToDo: createToDoReducer, 41 | deleteToDo: deleteToDoReducer, 42 | updateToDo: updateToDoReducer, 43 | setErrorMessage: setErrorMessageReducer, 44 | reset: resetReducer, 45 | }, 46 | }); 47 | 48 | export const { 49 | createToDo, 50 | deleteToDo, 51 | updateToDo, 52 | setErrorMessage, 53 | reset, 54 | } = toDoSlice.actions; 55 | 56 | export default toDoSlice.reducer; 57 | -------------------------------------------------------------------------------- /src/app/components/CustomSelect/CustomSelectInput.test.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { render, screen, fireEvent } from '@testing-library/react'; 3 | 4 | import { CustomSelect } from './CustomSelect'; 5 | 6 | const changeHandler = jest.fn(); 7 | 8 | const options = ['option 1', 'option 2']; 9 | 10 | test('renders the text input', () => { 11 | const { rerender, asFragment } = render( 12 | , 19 | ); 20 | expect(asFragment()).toMatchInlineSnapshot(` 21 | 22 | 23 | 26 | My Label 27 | 28 | 32 | 33 | option 1 34 | 35 | 36 | option 2 37 | 38 | 39 | 40 | 41 | `); 42 | const textInput = screen.getByLabelText('My Label'); 43 | expect(textInput).toHaveValue('option 2'); 44 | fireEvent.change(textInput, { target: { value: 'option 1' } }); 45 | expect(changeHandler).toHaveBeenCalledWith('option 1'); 46 | rerender( 47 | , 54 | ); 55 | expect(textInput).toHaveValue('option 1'); 56 | }); 57 | -------------------------------------------------------------------------------- /src/features/profile/profileSlice.ts: -------------------------------------------------------------------------------- 1 | import { createSlice } from '@reduxjs/toolkit'; 2 | 3 | import { createProfileReducer } from './reducers/createProfileReducer'; 4 | import { deleteProfileReducer } from './reducers/deleteProfileReducer'; 5 | import { updateProfileReducer } from './reducers/updateProfileReducer'; 6 | import { setActiveProfileReducer } from './reducers/setActiveProfileReducer'; 7 | 8 | import { resetReducer } from './reducers/resetReducer'; 9 | 10 | const profileTypes = ['guest', 'user', 'admin'] as const; // TS 3.4 11 | export type ProfileType = typeof profileTypes[number]; // union type 12 | 13 | export interface Profile { 14 | profileId: number; 15 | name?: string; 16 | profileType: ProfileType; 17 | showToDoList: boolean; 18 | } 19 | 20 | export interface ProfileState { 21 | profileList: Profile[]; 22 | maxProfileId: number; 23 | profileTypes: ReadonlyArray; 24 | activeProfileId?: number; 25 | } 26 | 27 | export const initialState: ProfileState = { 28 | profileList: [ 29 | { profileId: 1, name: 'Ben', profileType: 'admin', showToDoList: true }, 30 | { profileId: 2, name: 'Sue', profileType: 'user', showToDoList: false }, 31 | ], 32 | maxProfileId: 2, 33 | profileTypes: profileTypes as ReadonlyArray, 34 | }; 35 | 36 | export const profileSlice = createSlice({ 37 | name: 'profile', 38 | initialState, 39 | reducers: { 40 | createProfile: createProfileReducer, 41 | deleteProfile: deleteProfileReducer, 42 | updateProfile: updateProfileReducer, 43 | setActiveProfile: setActiveProfileReducer, 44 | reset: resetReducer, 45 | }, 46 | }); 47 | 48 | export const { 49 | createProfile, 50 | deleteProfile, 51 | updateProfile, 52 | setActiveProfile, 53 | reset, 54 | } = profileSlice.actions; 55 | 56 | export default profileSlice.reducer; 57 | -------------------------------------------------------------------------------- /public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 12 | 13 | 17 | 18 | 27 | React Redux App 28 | 29 | 30 | You need to enable JavaScript to run this app. 31 | 32 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /src/app/components/CustomCheckbox/CustomCheckbox.test.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { render, screen, fireEvent } from '@testing-library/react'; 3 | 4 | // this is the component we are going to be testing 5 | import { CustomCheckbox } from './CustomCheckbox'; 6 | 7 | // this is a event handler function that we will mock 8 | const changeHandler = jest.fn(); 9 | 10 | test('render the checkbox and click on it', () => { 11 | const { rerender, asFragment } = render( 12 | , 18 | ); 19 | // this is an inline snapshot. 20 | expect(asFragment()).toMatchInlineSnapshot(` 21 | 22 | 23 | 26 | My Label 27 | 28 | 33 | 34 | 35 | `); 36 | // React testing library encourages you to get elements the way a real user would-- 37 | // In this case, by the label. 38 | const checkbox = screen.getByLabelText('My Label'); 39 | 40 | // Our first event 41 | fireEvent.click(checkbox); 42 | expect(changeHandler).toHaveBeenCalledWith(true); 43 | 44 | // React testing library doesn't automatically rerender controlled form elements. 45 | // Instead we have to change the 'checked' prop and explicitly rerender. 46 | rerender( 47 | , 53 | ); 54 | 55 | // now when we click, the checkbox will be set to false 56 | fireEvent.click(checkbox); 57 | expect(changeHandler).toHaveBeenCalledWith(false); 58 | }); 59 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "unit-testing-react-redux", 3 | "version": "0.1.0", 4 | "private": true, 5 | "scripts": { 6 | "start": "react-scripts start", 7 | "build": "react-scripts build", 8 | "test": "react-scripts test", 9 | "test-ci": "react-scripts test --watchAll=false", 10 | "test-debug": "react-scripts --inspect-brk test --runInBand --no-cache", 11 | "coverage": "npm test -- --coverage --watchAll=false", 12 | "lint": "eslint --ext .ts --ext .tsx .", 13 | "eject": "react-scripts eject" 14 | }, 15 | "eslintConfig": { 16 | "extends": "react-app" 17 | }, 18 | "jest": { 19 | "collectCoverageFrom": [ 20 | "src/**/*.{ts,tsx}", 21 | "!/node_modules/", 22 | "!src/serviceWorker.ts", 23 | "!src/index.tsx" 24 | ] 25 | }, 26 | "browserslist": { 27 | "production": [ 28 | ">0.2%", 29 | "not dead", 30 | "not op_mini all" 31 | ], 32 | "development": [ 33 | "last 1 chrome version", 34 | "last 1 firefox version", 35 | "last 1 safari version" 36 | ] 37 | }, 38 | "dependencies": { 39 | "@reduxjs/toolkit": "^1.2.5", 40 | "@testing-library/jest-dom": "^4.2.4", 41 | "@testing-library/react": "^9.3.2", 42 | "@testing-library/user-event": "^7.1.2", 43 | "@types/jest": "^24.0.0", 44 | "@types/node": "^12.0.0", 45 | "@types/react-redux": "^7.1.7", 46 | "bootstrap": "^4.5.0", 47 | "classnames": "^2.2.6", 48 | "react": "^16.13.1", 49 | "react-bootstrap": "^1.1.1", 50 | "react-dom": "^16.13.1", 51 | "react-redux": "^7.2.0", 52 | "react-scripts": "3.4.1", 53 | "typescript": "~3.8.2" 54 | }, 55 | "devDependencies": { 56 | "@types/react": "^16.9.41", 57 | "@types/react-dom": "^16.9.8", 58 | "@types/webpack-env": "^1.15.2", 59 | "env-cmd": "^10.1.0", 60 | "eslint-config-prettier": "^6.11.0", 61 | "eslint-plugin-prettier": "^3.1.4", 62 | "eslint-plugin-sonarjs": "^0.5.0", 63 | "install": "^0.13.0", 64 | "npm": "^6.14.6", 65 | "prettier": "^2.0.5" 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/features/profile/components/ProfileItem/ProfileItem.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { useSelector } from 'react-redux'; 3 | import styles from './ProfileItem.module.css'; 4 | import classNames from 'classnames'; 5 | 6 | import { Profile } from '../../profileSlice'; 7 | import { CustomSelect } from 'app/components/CustomSelect/CustomSelect'; 8 | import { CustomTextInput } from 'app/components/CustomTextInput/CustomTextInput'; 9 | import { emptyProfile } from '../../helpers/profileTemplate'; 10 | import { profileTypesSelector } from '../../selectors/profileTypesSelector'; 11 | import { getIsActiveSelector } from '../../selectors/isActiveSelector'; 12 | import { getNameOnChange } from './getNameOnChange'; 13 | import { getTypeOnChange } from './getTypeOnChange'; 14 | import { getItemOnClick } from './getItemOnClick'; 15 | import { getDeleteOnClick } from './getDeleteOnClick'; 16 | 17 | interface ProfileProps { 18 | profile: Profile; 19 | } 20 | 21 | export const ProfileItem: React.FC = ({ 22 | profile = emptyProfile, 23 | }) => { 24 | const profileTypes = useSelector(profileTypesSelector); 25 | const isActive = useSelector(getIsActiveSelector(profile)); 26 | 27 | return ( 28 | 34 | 41 | 48 | 49 | 53 | Delete 54 | 55 | 56 | 57 | ); 58 | }; 59 | -------------------------------------------------------------------------------- /src/features/profile/components/ProfileCard/ProfileCard.test.tsx: -------------------------------------------------------------------------------- 1 | /* eslint-disable max-lines-per-function */ 2 | import React from 'react'; 3 | import { 4 | render, 5 | screen, 6 | within, 7 | RenderResult, 8 | fireEvent, 9 | } from '@testing-library/react'; 10 | import { Provider } from 'react-redux'; 11 | 12 | import { store } from 'app/store'; 13 | import { ProfileCard } from './ProfileCard'; 14 | import { reset } from '../../profileSlice'; 15 | 16 | const renderCard = (): RenderResult => 17 | render( 18 | 19 | 20 | , 21 | ); 22 | 23 | test('renders the Profile Card', () => { 24 | const { asFragment } = renderCard(); 25 | expect(asFragment()).toMatchSnapshot(); 26 | expect(screen.getByLabelText(/profile card/i)).toBeInTheDocument(); 27 | const profileList = screen.getByRole('list'); 28 | expect(profileList).toBeInTheDocument(); 29 | const profileListItems = within(profileList).getAllByRole('listitem'); 30 | expect(profileListItems).toHaveLength(2); 31 | }); 32 | 33 | test('test delete button', () => { 34 | const { rerender, asFragment } = renderCard(); 35 | const profileList = screen.getByRole('list'); 36 | let profileListItems = within(profileList).getAllByRole('listitem'); 37 | const deleteButton = within(profileListItems[0]).getByText(/delete/i); 38 | fireEvent.click(deleteButton); 39 | rerender( 40 | 41 | 42 | , 43 | ); 44 | profileListItems = within(profileList).getAllByRole('listitem'); 45 | expect(profileListItems).toHaveLength(1); 46 | expect(asFragment()).toMatchSnapshot(); 47 | }); 48 | 49 | test('test create button', () => { 50 | store.dispatch(reset()); 51 | const { rerender, asFragment } = renderCard(); 52 | const createButton = screen.getByText(/create/i); 53 | const profileList = screen.getByRole('list'); 54 | let profileListItems = within(profileList).getAllByRole('listitem'); 55 | expect(profileListItems).toHaveLength(2); 56 | fireEvent.click(createButton); 57 | rerender( 58 | 59 | 60 | , 61 | ); 62 | profileListItems = within(profileList).getAllByRole('listitem'); 63 | expect(profileListItems).toHaveLength(3); 64 | expect(asFragment()).toMatchSnapshot(); 65 | const lastItem = profileListItems[2]; 66 | expect(within(lastItem).getByLabelText('Name')).toHaveValue(''); 67 | expect(within(lastItem).getByLabelText('Type')).toHaveValue('guest'); 68 | }); 69 | -------------------------------------------------------------------------------- /src/features/profile/components/ProfileItem/ProfileItem.test.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { 3 | render /*, screen, within*/, 4 | screen, 5 | fireEvent, 6 | RenderResult, 7 | } from '@testing-library/react'; 8 | import { Provider } from 'react-redux'; 9 | 10 | import { store } from 'app/store'; 11 | import { ProfileItem } from './ProfileItem'; 12 | import { Profile } from 'features/profile/profileSlice'; 13 | 14 | const renderItem = (profile: Profile): RenderResult => 15 | render( 16 | 17 | 18 | , 19 | ); 20 | 21 | test('renders ProfileItem', () => { 22 | const profile = store.getState().profile.profileList[0]; 23 | const { asFragment } = renderItem(profile); 24 | expect(asFragment()).toMatchSnapshot(); 25 | }); 26 | 27 | test('ProfileItem name field', () => { 28 | let profile = store.getState().profile.profileList[0]; 29 | const { asFragment, rerender } = renderItem(profile); 30 | let textInput = screen.getByLabelText('Name'); 31 | expect(textInput).toHaveValue('Ben'); 32 | fireEvent.change(textInput, { target: { value: 'George' } }); 33 | 34 | textInput = screen.getByLabelText('Name'); 35 | profile = store.getState().profile.profileList[0]; 36 | expect(profile).toMatchInlineSnapshot(` 37 | Object { 38 | "name": "George", 39 | "profileId": 1, 40 | "profileType": "admin", 41 | "showToDoList": true, 42 | } 43 | `); 44 | rerender( 45 | 46 | 47 | , 48 | ); 49 | expect(textInput).toHaveValue('George'); 50 | expect(asFragment()).toMatchSnapshot(); 51 | }); 52 | 53 | test('ProfileItem type field', () => { 54 | let profile = store.getState().profile.profileList[0]; 55 | const { asFragment, rerender } = renderItem(profile); 56 | let typeSelect = screen.getByLabelText('Type'); 57 | expect(typeSelect).toHaveValue('admin'); 58 | fireEvent.change(typeSelect, { target: { value: 'user' } }); 59 | 60 | typeSelect = screen.getByLabelText('Type'); 61 | profile = store.getState().profile.profileList[0]; 62 | expect(profile).toMatchInlineSnapshot(` 63 | Object { 64 | "name": "George", 65 | "profileId": 1, 66 | "profileType": "user", 67 | "showToDoList": true, 68 | } 69 | `); 70 | rerender( 71 | 72 | 73 | , 74 | ); 75 | expect(typeSelect).toHaveValue('user'); 76 | expect(asFragment()).toMatchSnapshot(); 77 | }); 78 | -------------------------------------------------------------------------------- /src/features/toDo/components/ToDoCard/ToDoCard.test.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { 3 | render, 4 | screen, 5 | within, 6 | RenderResult, 7 | fireEvent, 8 | } from '@testing-library/react'; 9 | import { Provider } from 'react-redux'; 10 | 11 | import { store } from 'app/store'; 12 | import { ToDoCard } from './ToDoCard'; 13 | import { reset } from '../../toDoSlice'; 14 | import { setActiveProfile } from 'features/profile/profileSlice'; 15 | 16 | const renderCard = (): RenderResult => 17 | render( 18 | 19 | 20 | , 21 | ); 22 | 23 | test('renders the ToDoCard', () => { 24 | const { asFragment } = renderCard(); 25 | expect(asFragment()).toMatchSnapshot(); 26 | expect(screen.getByLabelText(/toDo card/i)).toBeInTheDocument(); 27 | const toDoList = screen.getByRole('list'); 28 | expect(toDoList).toBeInTheDocument(); 29 | 30 | // we have to use queryAll* instead of getAllBy* in order to test non-existence. 31 | // see https://stackoverflow.com/questions/52783144/how-do-you-test-for-the-non-existence-of-an-element-using-jest-and-react-testing 32 | const toDoListItems = within(toDoList).queryAllByRole('listitem'); 33 | expect(toDoListItems).toHaveLength(0); 34 | }); 35 | 36 | test('test delete button', () => { 37 | store.dispatch(setActiveProfile(1)); 38 | const { rerender, asFragment } = renderCard(); 39 | const toDoList = screen.getByRole('list'); 40 | let toDoListItems = within(toDoList).getAllByRole('listitem'); 41 | const deleteButton = within(toDoListItems[0]).getByText(/delete/i); 42 | fireEvent.click(deleteButton); 43 | rerender( 44 | 45 | 46 | , 47 | ); 48 | toDoListItems = within(toDoList).getAllByRole('listitem'); 49 | expect(toDoListItems).toHaveLength(2); 50 | expect(asFragment()).toMatchSnapshot(); 51 | }); 52 | 53 | test('test create button', () => { 54 | store.dispatch(reset()); 55 | store.dispatch(setActiveProfile(1)); 56 | const { rerender, asFragment } = renderCard(); 57 | const createButton = screen.getByText(/create/i); 58 | const toDoList = screen.getByRole('list'); 59 | let toDoListItems = within(toDoList).getAllByRole('listitem'); 60 | expect(toDoListItems).toHaveLength(3); 61 | fireEvent.click(createButton); 62 | rerender( 63 | 64 | 65 | , 66 | ); 67 | toDoListItems = within(toDoList).getAllByRole('listitem'); 68 | expect(toDoListItems).toHaveLength(4); 69 | expect(asFragment()).toMatchSnapshot(); 70 | const lastItem = toDoListItems[3]; 71 | expect(within(lastItem).getByLabelText(/complete/i)).not.toBeChecked(); 72 | expect(within(lastItem).getByLabelText(/description/i)).toHaveValue(''); 73 | }); 74 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | This project is a demo of my opinions for best practices for React, Redux, and React Testing Library, and using Visual Studio code as the editor. 2 | 3 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app), using the [Redux](https://redux.js.org/) and [Redux Toolkit](https://redux-toolkit.js.org/) template. 4 | 5 | ## Available Scripts 6 | 7 | In the project directory, you can run: 8 | 9 | ### `npm start` 10 | 11 | Runs the app in the development mode. 12 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser. 13 | 14 | The page will reload if you make edits. 15 | You will also see any lint errors in the console. 16 | 17 | ### `npm test` 18 | 19 | Launches the test runner in the interactive watch mode. 20 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. 21 | 22 | ### `npm test-ci` 23 | 24 | Launches the test runner in Continuous Integration mode. (Does not watch for changes) 25 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. 26 | 27 | ### `npm run test-debug` 28 | 29 | This will start running your Jest tests, but pause before executing to allow a debugger to attach to the process. See [](https://create-react-app.dev/docs/debugging-tests/) 30 | 31 | ### `npm run build` 32 | 33 | Builds the app for production to the `build` folder. 34 | It correctly bundles React in production mode and optimizes the build for the best performance. 35 | 36 | The build is minified and the filenames include the hashes. 37 | Your app is ready to be deployed! 38 | 39 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. 40 | 41 | ### `npm run coverage` 42 | 43 | Runs test coverage. 44 | 45 | ### `npm run eject` 46 | 47 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!** 48 | 49 | If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. 50 | 51 | Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own. 52 | 53 | You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. 54 | 55 | ## Learn More 56 | 57 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). 58 | 59 | To learn React, check out the [React documentation](https://reactjs.org/). 60 | -------------------------------------------------------------------------------- /src/features/toDo/components/ToDoItem/__snapshots__/ToDoItem.test.tsx.snap: -------------------------------------------------------------------------------- 1 | // Jest Snapshot v1, https://goo.gl/fbAQLP 2 | 3 | exports[`ToDoItem description field 2`] = ` 4 | 5 | 8 | 9 | 12 | Complete? 13 | 14 | 20 | 21 | 22 | 25 | Description 26 | 27 | 33 | 34 | 37 | 40 | Delete 41 | 42 | 43 | 44 | 45 | `; 46 | 47 | exports[`ToDoItem isComplete field 2`] = ` 48 | 49 | 52 | 53 | 56 | Complete? 57 | 58 | 64 | 65 | 66 | 69 | Description 70 | 71 | 77 | 78 | 81 | 84 | Delete 85 | 86 | 87 | 88 | 89 | `; 90 | 91 | exports[`renders ToDoItem 1`] = ` 92 | 93 | 96 | 97 | 100 | Complete? 101 | 102 | 108 | 109 | 110 | 113 | Description 114 | 115 | 121 | 122 | 125 | 128 | Delete 129 | 130 | 131 | 132 | 133 | `; 134 | -------------------------------------------------------------------------------- /src/app/components/App/App.test.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { 3 | render, 4 | screen, 5 | within, 6 | fireEvent, 7 | RenderResult, 8 | } from '@testing-library/react'; 9 | import { Provider } from 'react-redux'; 10 | 11 | import { store } from 'app/store'; 12 | import App from './App'; 13 | 14 | const renderApp = (): RenderResult => 15 | render( 16 | 17 | 18 | , 19 | ); 20 | 21 | test('renders the app', () => { 22 | const { asFragment } = renderApp(); 23 | expect(asFragment()).toMatchSnapshot(); 24 | expect(screen.getByLabelText(/profile card/i)).toBeInTheDocument(); 25 | expect(screen.getByLabelText(/todo card/i)).toBeInTheDocument(); 26 | }); 27 | 28 | test('handles profile click', () => { 29 | const { asFragment } = renderApp(); 30 | const profileCard = screen.getByLabelText(/profile card/i); 31 | const profileList = within(profileCard).getByRole('list'); 32 | const profileListItems = within(profileList).getAllByRole('listitem'); 33 | 34 | const toDoCard = screen.getByLabelText(/todo card/i); 35 | const toDoList = within(toDoCard).getByRole('list'); 36 | let toDoListItems = within(toDoList).queryAllByRole('listitem'); 37 | expect(toDoListItems).toHaveLength(0); 38 | 39 | fireEvent.click(profileListItems[0]); 40 | toDoListItems = within(toDoList).queryAllByRole('listitem'); 41 | expect(toDoListItems).toHaveLength(3); 42 | expect(asFragment()).toMatchSnapshot(); 43 | }); 44 | 45 | test('handles profile delete click', () => { 46 | const { asFragment } = renderApp(); 47 | const profileCard = screen.getByLabelText(/profile card/i); 48 | const profileList = within(profileCard).getByRole('list'); 49 | const profileListItems = within(profileList).getAllByRole('listitem'); 50 | fireEvent.click(profileListItems[0]); 51 | 52 | // here we want to use getBy* instead of queryBy* because we expect the element to exist 53 | // if it doesn't, test will fail instead of exception thrown, which is what we want. 54 | const profileDeleteButton = within(profileListItems[0]).getByText(/delete/i); 55 | 56 | fireEvent.click(profileDeleteButton); 57 | const toDoCard = screen.getByLabelText(/todo card/i); 58 | const toDoList = within(toDoCard).getByRole('list'); 59 | const toDoListItems = within(toDoList).queryAllByRole('listitem'); 60 | expect(toDoListItems).toHaveLength(0); 61 | expect(asFragment()).toMatchSnapshot(); 62 | }); 63 | 64 | test('handles create new todo click', () => { 65 | const { rerender } = renderApp(); 66 | let alert = screen.queryByRole(/alert/i); 67 | expect(alert).not.toBeInTheDocument(); 68 | const createNewToDoButton = screen.getByText(/create new todo/i); 69 | fireEvent.click(createNewToDoButton); 70 | rerender( 71 | 72 | 73 | , 74 | ); 75 | alert = screen.getByRole(/alert/i); 76 | expect(alert).toBeInTheDocument(); 77 | const alertCloseButton = within(alert).getByRole('button'); 78 | fireEvent.click(alertCloseButton); 79 | rerender( 80 | 81 | 82 | , 83 | ); 84 | expect(alert).not.toBeInTheDocument(); 85 | }); 86 | -------------------------------------------------------------------------------- /src/features/toDo/components/ToDoItem/ToDoItem.test.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { 3 | render, 4 | screen, 5 | fireEvent, 6 | RenderResult, 7 | } from '@testing-library/react'; 8 | import { Provider } from 'react-redux'; 9 | 10 | import { store } from 'app/store'; 11 | import { ToDoItem } from './ToDoItem'; 12 | import { ToDo, reset } from 'features/toDo/toDoSlice'; 13 | 14 | const renderItem = (toDo: ToDo): RenderResult => 15 | // the ToDoItem component is now "reduxified" 16 | render( 17 | 18 | 19 | , 20 | ); 21 | 22 | const getToDo = (toDoId: number): ToDo => { 23 | const toDo = store.getState().toDo.toDoList.find((p) => p.toDoId === toDoId); 24 | expect(toDo).not.toBeUndefined(); 25 | // typescript doesn't understand that ToDo must be defined here, so we explicitly cast 26 | return toDo as ToDo; 27 | }; 28 | 29 | test('renders ToDoItem', () => { 30 | const toDo = getToDo(1); 31 | const { asFragment } = renderItem(toDo); 32 | expect(asFragment()).toMatchSnapshot(); 33 | }); 34 | 35 | test('ToDoItem description field', () => { 36 | let toDo = getToDo(1); 37 | const { asFragment, rerender } = renderItem(toDo); 38 | let textInput = screen.getByLabelText('Description'); 39 | expect(textInput).toHaveValue('eat tacos'); 40 | fireEvent.change(textInput, { target: { value: 'live, laugh, love' } }); 41 | 42 | textInput = screen.getByLabelText('Description'); 43 | toDo = getToDo(1); 44 | expect(toDo).toMatchInlineSnapshot(` 45 | Object { 46 | "description": "live, laugh, love", 47 | "isComplete": true, 48 | "profileId": 1, 49 | "toDoId": 1, 50 | } 51 | `); 52 | 53 | // it is necessary to reduxify the component when you rerender also 54 | rerender( 55 | 56 | 57 | , 58 | ); 59 | expect(textInput).toHaveValue('live, laugh, love'); 60 | expect(asFragment()).toMatchSnapshot(); 61 | }); 62 | 63 | test('ToDoItem isComplete field', () => { 64 | // Whenever you do multiple redux tests in the same file, it's best practice to reset the state. 65 | // Otherwise the state from a previous test could bleed into a new one and cause unexpected issues. 66 | store.dispatch(reset()); 67 | let toDo = getToDo(1); 68 | const { asFragment, rerender } = renderItem(toDo); 69 | 70 | // It's best practice to get an element the same way a real user would get an element. 71 | // In this case by the label text. 72 | const isCompleteCheckbox = screen.getByLabelText(/complete/i); 73 | expect(isCompleteCheckbox).toBeChecked(); 74 | 75 | // this is how we check/uncheck a checkbox 76 | fireEvent.click(isCompleteCheckbox); 77 | toDo = getToDo(1); 78 | expect(toDo).toMatchInlineSnapshot(` 79 | Object { 80 | "description": "eat tacos", 81 | "isComplete": false, 82 | "profileId": 1, 83 | "toDoId": 1, 84 | } 85 | `); 86 | 87 | // it is necessary to reduxify the component when you rerender also 88 | rerender( 89 | 90 | 91 | , 92 | ); 93 | expect(isCompleteCheckbox).not.toBeChecked(); 94 | expect(asFragment()).toMatchSnapshot(); 95 | }); 96 | -------------------------------------------------------------------------------- /src/features/profile/components/ProfileItem/__snapshots__/ProfileItem.test.tsx.snap: -------------------------------------------------------------------------------- 1 | // Jest Snapshot v1, https://goo.gl/fbAQLP 2 | 3 | exports[`ProfileItem name field 2`] = ` 4 | 5 | 8 | 9 | 12 | Name 13 | 14 | 20 | 21 | 22 | 25 | Type 26 | 27 | 31 | 32 | guest 33 | 34 | 35 | user 36 | 37 | 38 | admin 39 | 40 | 41 | 42 | 45 | 48 | Delete 49 | 50 | 51 | 52 | 53 | `; 54 | 55 | exports[`ProfileItem type field 2`] = ` 56 | 57 | 60 | 61 | 64 | Name 65 | 66 | 72 | 73 | 74 | 77 | Type 78 | 79 | 83 | 84 | guest 85 | 86 | 87 | user 88 | 89 | 90 | admin 91 | 92 | 93 | 94 | 97 | 100 | Delete 101 | 102 | 103 | 104 | 105 | `; 106 | 107 | exports[`renders ProfileItem 1`] = ` 108 | 109 | 112 | 113 | 116 | Name 117 | 118 | 124 | 125 | 126 | 129 | Type 130 | 131 | 135 | 136 | guest 137 | 138 | 139 | user 140 | 141 | 142 | admin 143 | 144 | 145 | 146 | 149 | 152 | Delete 153 | 154 | 155 | 156 | 157 | `; 158 | -------------------------------------------------------------------------------- /src/serviceWorker.ts: -------------------------------------------------------------------------------- 1 | // This optional code is used to register a service worker. 2 | // register() is not called by default. 3 | 4 | // This lets the app load faster on subsequent visits in production, and gives 5 | // it offline capabilities. However, it also means that developers (and users) 6 | // will only see deployed updates on subsequent visits to a page, after all the 7 | // existing tabs open on the page have been closed, since previously cached 8 | // resources are updated in the background. 9 | 10 | // To learn more about the benefits of this model and instructions on how to 11 | // opt-in, read https://bit.ly/CRA-PWA 12 | 13 | const isLocalhost = Boolean( 14 | window.location.hostname === 'localhost' || 15 | // [::1] is the IPv6 localhost address. 16 | window.location.hostname === '[::1]' || 17 | // 127.0.0.0/8 are considered localhost for IPv4. 18 | window.location.hostname.match( 19 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/, 20 | ), 21 | ); 22 | 23 | type Config = { 24 | onSuccess?: (registration: ServiceWorkerRegistration) => void; 25 | onUpdate?: (registration: ServiceWorkerRegistration) => void; 26 | }; 27 | 28 | export function register(config?: Config) { 29 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) { 30 | // The URL constructor is available in all browsers that support SW. 31 | const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href); 32 | if (publicUrl.origin !== window.location.origin) { 33 | // Our service worker won't work if PUBLIC_URL is on a different origin 34 | // from what our page is served on. This might happen if a CDN is used to 35 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374 36 | return; 37 | } 38 | 39 | window.addEventListener('load', () => { 40 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; 41 | 42 | if (isLocalhost) { 43 | // This is running on localhost. Let's check if a service worker still exists or not. 44 | checkValidServiceWorker(swUrl, config); 45 | 46 | // Add some additional logging to localhost, pointing developers to the 47 | // service worker/PWA documentation. 48 | navigator.serviceWorker.ready.then(() => { 49 | console.log( 50 | 'This web app is being served cache-first by a service ' + 51 | 'worker. To learn more, visit https://bit.ly/CRA-PWA', 52 | ); 53 | }); 54 | } else { 55 | // Is not localhost. Just register service worker 56 | registerValidSW(swUrl, config); 57 | } 58 | }); 59 | } 60 | } 61 | 62 | function registerValidSW(swUrl: string, config?: Config) { 63 | navigator.serviceWorker 64 | .register(swUrl) 65 | .then((registration) => { 66 | registration.onupdatefound = () => { 67 | const installingWorker = registration.installing; 68 | if (installingWorker == null) { 69 | return; 70 | } 71 | installingWorker.onstatechange = () => { 72 | if (installingWorker.state === 'installed') { 73 | if (navigator.serviceWorker.controller) { 74 | // At this point, the updated precached content has been fetched, 75 | // but the previous service worker will still serve the older 76 | // content until all client tabs are closed. 77 | console.log( 78 | 'New content is available and will be used when all ' + 79 | 'tabs for this page are closed. See https://bit.ly/CRA-PWA.', 80 | ); 81 | 82 | // Execute callback 83 | if (config && config.onUpdate) { 84 | config.onUpdate(registration); 85 | } 86 | } else { 87 | // At this point, everything has been precached. 88 | // It's the perfect time to display a 89 | // "Content is cached for offline use." message. 90 | console.log('Content is cached for offline use.'); 91 | 92 | // Execute callback 93 | if (config && config.onSuccess) { 94 | config.onSuccess(registration); 95 | } 96 | } 97 | } 98 | }; 99 | }; 100 | }) 101 | .catch((error) => { 102 | console.error('Error during service worker registration:', error); 103 | }); 104 | } 105 | 106 | function checkValidServiceWorker(swUrl: string, config?: Config) { 107 | // Check if the service worker can be found. If it can't reload the page. 108 | fetch(swUrl, { 109 | headers: { 'Service-Worker': 'script' }, 110 | }) 111 | .then((response) => { 112 | // Ensure service worker exists, and that we really are getting a JS file. 113 | const contentType = response.headers.get('content-type'); 114 | if ( 115 | response.status === 404 || 116 | (contentType != null && contentType.indexOf('javascript') === -1) 117 | ) { 118 | // No service worker found. Probably a different app. Reload the page. 119 | navigator.serviceWorker.ready.then((registration) => { 120 | registration.unregister().then(() => { 121 | window.location.reload(); 122 | }); 123 | }); 124 | } else { 125 | // Service worker found. Proceed as normal. 126 | registerValidSW(swUrl, config); 127 | } 128 | }) 129 | .catch(() => { 130 | console.log( 131 | 'No internet connection found. App is running in offline mode.', 132 | ); 133 | }); 134 | } 135 | 136 | export function unregister() { 137 | if ('serviceWorker' in navigator) { 138 | navigator.serviceWorker.ready 139 | .then((registration) => { 140 | registration.unregister(); 141 | }) 142 | .catch((error) => { 143 | console.error(error.message); 144 | }); 145 | } 146 | } 147 | -------------------------------------------------------------------------------- /src/features/toDo/components/ToDoCard/__snapshots__/ToDoCard.test.tsx.snap: -------------------------------------------------------------------------------- 1 | // Jest Snapshot v1, https://goo.gl/fbAQLP 2 | 3 | exports[`renders the ToDoCard 1`] = ` 4 | 5 | 10 | 13 | 16 | ToDos 17 | 18 | 19 | 22 | 25 | 26 | 39 | 40 | 41 | `; 42 | 43 | exports[`test create button 1`] = ` 44 | 45 | 50 | 53 | 56 | ToDos for Ben 57 | 58 | 59 | 62 | 65 | 68 | 69 | 72 | Complete? 73 | 74 | 80 | 81 | 82 | 85 | Description 86 | 87 | 93 | 94 | 97 | 100 | Delete 101 | 102 | 103 | 104 | 107 | 108 | 111 | Complete? 112 | 113 | 118 | 119 | 120 | 123 | Description 124 | 125 | 131 | 132 | 135 | 138 | Delete 139 | 140 | 141 | 142 | 145 | 146 | 149 | Complete? 150 | 151 | 156 | 157 | 158 | 161 | Description 162 | 163 | 169 | 170 | 173 | 176 | Delete 177 | 178 | 179 | 180 | 183 | 184 | 187 | Complete? 188 | 189 | 194 | 195 | 196 | 199 | Description 200 | 201 | 207 | 208 | 211 | 214 | Delete 215 | 216 | 217 | 218 | 219 | 220 | 233 | 234 | 235 | `; 236 | 237 | exports[`test delete button 1`] = ` 238 | 239 | 244 | 247 | 250 | ToDos for Ben 251 | 252 | 253 | 256 | 259 | 262 | 263 | 266 | Complete? 267 | 268 | 273 | 274 | 275 | 278 | Description 279 | 280 | 286 | 287 | 290 | 293 | Delete 294 | 295 | 296 | 297 | 300 | 301 | 304 | Complete? 305 | 306 | 311 | 312 | 313 | 316 | Description 317 | 318 | 324 | 325 | 328 | 331 | Delete 332 | 333 | 334 | 335 | 336 | 337 | 350 | 351 | 352 | `; 353 | -------------------------------------------------------------------------------- /src/features/profile/components/ProfileCard/__snapshots__/ProfileCard.test.tsx.snap: -------------------------------------------------------------------------------- 1 | // Jest Snapshot v1, https://goo.gl/fbAQLP 2 | 3 | exports[`renders the Profile Card 1`] = ` 4 | 5 | 10 | 13 | 16 | Profiles 17 | 18 | 19 | 22 | 25 | 28 | 29 | 32 | Name 33 | 34 | 40 | 41 | 42 | 45 | Type 46 | 47 | 51 | 52 | guest 53 | 54 | 55 | user 56 | 57 | 58 | admin 59 | 60 | 61 | 62 | 65 | 68 | Delete 69 | 70 | 71 | 72 | 75 | 76 | 79 | Name 80 | 81 | 87 | 88 | 89 | 92 | Type 93 | 94 | 98 | 99 | guest 100 | 101 | 102 | user 103 | 104 | 105 | admin 106 | 107 | 108 | 109 | 112 | 115 | Delete 116 | 117 | 118 | 119 | 120 | 121 | 134 | 135 | 136 | `; 137 | 138 | exports[`test create button 1`] = ` 139 | 140 | 145 | 148 | 151 | Profiles 152 | 153 | 154 | 157 | 160 | 163 | 164 | 167 | Name 168 | 169 | 175 | 176 | 177 | 180 | Type 181 | 182 | 186 | 187 | guest 188 | 189 | 190 | user 191 | 192 | 193 | admin 194 | 195 | 196 | 197 | 200 | 203 | Delete 204 | 205 | 206 | 207 | 210 | 211 | 214 | Name 215 | 216 | 222 | 223 | 224 | 227 | Type 228 | 229 | 233 | 234 | guest 235 | 236 | 237 | user 238 | 239 | 240 | admin 241 | 242 | 243 | 244 | 247 | 250 | Delete 251 | 252 | 253 | 254 | 257 | 258 | 261 | Name 262 | 263 | 269 | 270 | 271 | 274 | Type 275 | 276 | 280 | 281 | guest 282 | 283 | 284 | user 285 | 286 | 287 | admin 288 | 289 | 290 | 291 | 294 | 297 | Delete 298 | 299 | 300 | 301 | 302 | 303 | 316 | 317 | 318 | `; 319 | 320 | exports[`test delete button 1`] = ` 321 | 322 | 327 | 330 | 333 | Profiles 334 | 335 | 336 | 339 | 342 | 345 | 346 | 349 | Name 350 | 351 | 357 | 358 | 359 | 362 | Type 363 | 364 | 368 | 369 | guest 370 | 371 | 372 | user 373 | 374 | 375 | admin 376 | 377 | 378 | 379 | 382 | 385 | Delete 386 | 387 | 388 | 389 | 390 | 391 | 404 | 405 | 406 | `; 407 | -------------------------------------------------------------------------------- /src/app/components/App/__snapshots__/App.test.tsx.snap: -------------------------------------------------------------------------------- 1 | // Jest Snapshot v1, https://goo.gl/fbAQLP 2 | 3 | exports[`handles profile click 1`] = ` 4 | 5 | 8 | 13 | 16 | 19 | Profiles 20 | 21 | 22 | 25 | 28 | 31 | 32 | 35 | Name 36 | 37 | 44 | 45 | 46 | 49 | Type 50 | 51 | 55 | 56 | guest 57 | 58 | 59 | user 60 | 61 | 62 | admin 63 | 64 | 65 | 66 | 69 | 72 | Delete 73 | 74 | 75 | 76 | 79 | 80 | 83 | Name 84 | 85 | 91 | 92 | 93 | 96 | Type 97 | 98 | 102 | 103 | guest 104 | 105 | 106 | user 107 | 108 | 109 | admin 110 | 111 | 112 | 113 | 116 | 119 | Delete 120 | 121 | 122 | 123 | 124 | 125 | 138 | 139 | 144 | 147 | 150 | ToDos for Ben 151 | 152 | 153 | 156 | 159 | 162 | 163 | 166 | Complete? 167 | 168 | 174 | 175 | 176 | 179 | Description 180 | 181 | 187 | 188 | 191 | 194 | Delete 195 | 196 | 197 | 198 | 201 | 202 | 205 | Complete? 206 | 207 | 212 | 213 | 214 | 217 | Description 218 | 219 | 225 | 226 | 229 | 232 | Delete 233 | 234 | 235 | 236 | 239 | 240 | 243 | Complete? 244 | 245 | 250 | 251 | 252 | 255 | Description 256 | 257 | 263 | 264 | 267 | 270 | Delete 271 | 272 | 273 | 274 | 275 | 276 | 289 | 290 | 291 | 292 | `; 293 | 294 | exports[`handles profile delete click 1`] = ` 295 | 296 | 299 | 304 | 307 | 310 | Profiles 311 | 312 | 313 | 316 | 319 | 322 | 323 | 326 | Name 327 | 328 | 334 | 335 | 336 | 339 | Type 340 | 341 | 345 | 346 | guest 347 | 348 | 349 | user 350 | 351 | 352 | admin 353 | 354 | 355 | 356 | 359 | 362 | Delete 363 | 364 | 365 | 366 | 367 | 368 | 381 | 382 | 387 | 390 | 393 | ToDos 394 | 395 | 396 | 399 | 402 | 403 | 416 | 417 | 418 | 419 | `; 420 | 421 | exports[`renders the app 1`] = ` 422 | 423 | 426 | 431 | 434 | 437 | Profiles 438 | 439 | 440 | 443 | 446 | 449 | 450 | 453 | Name 454 | 455 | 461 | 462 | 463 | 466 | Type 467 | 468 | 472 | 473 | guest 474 | 475 | 476 | user 477 | 478 | 479 | admin 480 | 481 | 482 | 483 | 486 | 489 | Delete 490 | 491 | 492 | 493 | 496 | 497 | 500 | Name 501 | 502 | 508 | 509 | 510 | 513 | Type 514 | 515 | 519 | 520 | guest 521 | 522 | 523 | user 524 | 525 | 526 | admin 527 | 528 | 529 | 530 | 533 | 536 | Delete 537 | 538 | 539 | 540 | 541 | 542 | 555 | 556 | 561 | 564 | 567 | ToDos 568 | 569 | 570 | 573 | 576 | 577 | 590 | 591 | 592 | 593 | `; 594 | --------------------------------------------------------------------------------