├── .gitignore ├── README.md ├── package.json ├── public ├── favicon.ico ├── index.html ├── logo192.png ├── logo512.png ├── manifest.json └── robots.txt ├── src ├── App.css ├── App.js ├── App.test.js ├── index.css ├── index.js ├── logo.svg ├── reportWebVitals.js ├── setupTests.js ├── store │ ├── index.js │ └── slices │ │ ├── user.js │ │ └── user.test.js └── utils │ └── tests.data.js └── yarn.lock /.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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Getting Started with Create React App 2 | 3 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). 4 | 5 | ## Available Scripts 6 | 7 | In the project directory, you can run: 8 | 9 | ### `yarn start` 10 | 11 | Runs the app in the development mode.\ 12 | Open [http://localhost:3000](http://localhost:3000) to view it in your browser. 13 | 14 | The page will reload when you make changes.\ 15 | You may also see any lint errors in the console. 16 | 17 | ### `yarn 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 | ### `yarn build` 23 | 24 | Builds the app for production to the `build` folder.\ 25 | It correctly bundles React in production mode and optimizes the build for the best performance. 26 | 27 | The build is minified and the filenames include the hashes.\ 28 | Your app is ready to be deployed! 29 | 30 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. 31 | 32 | ### `yarn eject` 33 | 34 | **Note: this is a one-way operation. Once you `eject`, you can't go back!** 35 | 36 | 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. 37 | 38 | 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. 39 | 40 | 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. 41 | 42 | ## Learn More 43 | 44 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). 45 | 46 | To learn React, check out the [React documentation](https://reactjs.org/). 47 | 48 | ### Code Splitting 49 | 50 | This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting) 51 | 52 | ### Analyzing the Bundle Size 53 | 54 | This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size) 55 | 56 | ### Making a Progressive Web App 57 | 58 | This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app) 59 | 60 | ### Advanced Configuration 61 | 62 | This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration) 63 | 64 | ### Deployment 65 | 66 | This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment) 67 | 68 | ### `yarn build` fails to minify 69 | 70 | This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify) 71 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-redux-test-driven-development", 3 | "version": "0.1.0", 4 | "private": true, 5 | "dependencies": { 6 | "@reduxjs/toolkit": "^1.8.1", 7 | "@testing-library/jest-dom": "^5.14.1", 8 | "@testing-library/react": "^13.0.0", 9 | "@testing-library/user-event": "^13.2.1", 10 | "axios": "^0.26.1", 11 | "axios-mock-adapter": "^1.20.0", 12 | "react": "^18.0.0", 13 | "react-dom": "^18.0.0", 14 | "react-redux": "^8.0.0", 15 | "react-scripts": "5.0.1", 16 | "redux": "^4.1.2", 17 | "web-vitals": "^2.1.0" 18 | }, 19 | "scripts": { 20 | "start": "react-scripts start", 21 | "build": "react-scripts build", 22 | "test": "react-scripts test", 23 | "eject": "react-scripts eject" 24 | }, 25 | "eslintConfig": { 26 | "extends": [ 27 | "react-app", 28 | "react-app/jest" 29 | ] 30 | }, 31 | "browserslist": { 32 | "production": [ 33 | ">0.2%", 34 | "not dead", 35 | "not op_mini all" 36 | ], 37 | "development": [ 38 | "last 1 chrome version", 39 | "last 1 firefox version", 40 | "last 1 safari version" 41 | ] 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/koladev32/react-redux-test-driven-development/a84f36d8668063af83da056d9ede3d51f1bca8c9/public/favicon.ico -------------------------------------------------------------------------------- /public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 12 | 13 | 17 | 18 | 27 | React App 28 | 29 | 30 | 31 |
32 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /public/logo192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/koladev32/react-redux-test-driven-development/a84f36d8668063af83da056d9ede3d51f1bca8c9/public/logo192.png -------------------------------------------------------------------------------- /public/logo512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/koladev32/react-redux-test-driven-development/a84f36d8668063af83da056d9ede3d51f1bca8c9/public/logo512.png -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /public/robots.txt: -------------------------------------------------------------------------------- 1 | # https://www.robotstxt.org/robotstxt.html 2 | User-agent: * 3 | Disallow: 4 | -------------------------------------------------------------------------------- /src/App.css: -------------------------------------------------------------------------------- 1 | .App { 2 | text-align: center; 3 | } 4 | 5 | .App-logo { 6 | height: 40vmin; 7 | pointer-events: none; 8 | } 9 | 10 | @media (prefers-reduced-motion: no-preference) { 11 | .App-logo { 12 | animation: App-logo-spin infinite 20s linear; 13 | } 14 | } 15 | 16 | .App-header { 17 | background-color: #282c34; 18 | min-height: 100vh; 19 | display: flex; 20 | flex-direction: column; 21 | align-items: center; 22 | justify-content: center; 23 | font-size: calc(10px + 2vmin); 24 | color: white; 25 | } 26 | 27 | .App-link { 28 | color: #61dafb; 29 | } 30 | 31 | @keyframes App-logo-spin { 32 | from { 33 | transform: rotate(0deg); 34 | } 35 | to { 36 | transform: rotate(360deg); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/App.js: -------------------------------------------------------------------------------- 1 | import logo from './logo.svg'; 2 | import './App.css'; 3 | 4 | function App() { 5 | return ( 6 |
7 |
8 | logo 9 |

10 | Edit src/App.js and save to reload. 11 |

12 | 18 | Learn React 19 | 20 |
21 |
22 | ); 23 | } 24 | 25 | export default App; 26 | -------------------------------------------------------------------------------- /src/App.test.js: -------------------------------------------------------------------------------- 1 | import { render, screen } from '@testing-library/react'; 2 | import App from './App'; 3 | 4 | test('renders learn react link', () => { 5 | render(); 6 | const linkElement = screen.getByText(/learn react/i); 7 | expect(linkElement).toBeInTheDocument(); 8 | }); 9 | -------------------------------------------------------------------------------- /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/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom/client'; 3 | import './index.css'; 4 | import App from './App'; 5 | import reportWebVitals from './reportWebVitals'; 6 | 7 | const root = ReactDOM.createRoot(document.getElementById('root')); 8 | root.render( 9 | 10 | 11 | 12 | ); 13 | 14 | // If you want to start measuring performance in your app, pass a function 15 | // to log results (for example: reportWebVitals(console.log)) 16 | // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals 17 | reportWebVitals(); 18 | -------------------------------------------------------------------------------- /src/logo.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/reportWebVitals.js: -------------------------------------------------------------------------------- 1 | const reportWebVitals = onPerfEntry => { 2 | if (onPerfEntry && onPerfEntry instanceof Function) { 3 | import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => { 4 | getCLS(onPerfEntry); 5 | getFID(onPerfEntry); 6 | getFCP(onPerfEntry); 7 | getLCP(onPerfEntry); 8 | getTTFB(onPerfEntry); 9 | }); 10 | } 11 | }; 12 | 13 | export default reportWebVitals; 14 | -------------------------------------------------------------------------------- /src/setupTests.js: -------------------------------------------------------------------------------- 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'; 6 | -------------------------------------------------------------------------------- /src/store/index.js: -------------------------------------------------------------------------------- 1 | import { configureStore } from "@reduxjs/toolkit"; 2 | import { combineReducers } from "redux"; 3 | import { userSlice } from "./slices/user"; 4 | 5 | const rootReducer = combineReducers({ 6 | users: userSlice.reducer, 7 | }); 8 | 9 | export const store = configureStore({ 10 | reducer: rootReducer, 11 | }); -------------------------------------------------------------------------------- /src/store/slices/user.js: -------------------------------------------------------------------------------- 1 | import { createAsyncThunk, createSlice } from "@reduxjs/toolkit"; 2 | import axios from "axios"; 3 | 4 | const fetchUsers = createAsyncThunk( 5 | "users/fetchUsers", 6 | async () => { 7 | const response = await axios.get(`/users/`); 8 | return response.data; 9 | } 10 | ); 11 | 12 | const addUser = createAsyncThunk("users/addUser", async (user) => { 13 | const res = await axios.post(`/users/`, user); 14 | return res.data; 15 | }); 16 | 17 | const updateUser = createAsyncThunk("users/updateUser", async (user) => { 18 | const res = await axios.put(`/users/${user.id}`, user); 19 | return res.data; 20 | }); 21 | 22 | const deleteUser = createAsyncThunk("users/deleteUser", async (user) => { 23 | await axios.delete(`/users/${user.id}`); 24 | return user; 25 | }); 26 | 27 | const findUserById = createAsyncThunk( 28 | "users/findUserById", 29 | async (id) => { 30 | const res = await axios.get(`/users/?id=${id}`); 31 | return res.data; 32 | } 33 | ); 34 | 35 | 36 | export const initialState = { 37 | users: [], 38 | loading: false, 39 | error: null, 40 | selectedUser: null, 41 | }; 42 | 43 | export const userSlice = createSlice({ 44 | name: "users", 45 | initialState: initialState, 46 | extraReducers: (builder) => { 47 | /* 48 | * addUser Cases 49 | */ 50 | 51 | builder.addCase(addUser.pending, (state) => { 52 | state.loading = true; 53 | }); 54 | builder.addCase(addUser.rejected, (state, action) => { 55 | state.loading = false; 56 | state.error = action.error.message || "Something went wrong"; 57 | }); 58 | builder.addCase(addUser.fulfilled, (state, action) => { 59 | state.loading = true; 60 | state.users.push(action.payload); 61 | }); 62 | 63 | /* 64 | * updateUser Cases 65 | */ 66 | 67 | builder.addCase(updateUser.pending, (state) => { 68 | state.loading = true; 69 | }); 70 | builder.addCase(updateUser.rejected, (state, action) => { 71 | state.loading = false; 72 | state.error = action.error.message || "Something went wrong"; 73 | }); 74 | builder.addCase(updateUser.fulfilled, (state, action) => { 75 | state.loading = true; 76 | state.users = state.users.map((user) => { 77 | if (user.id === action.payload.id) { 78 | return action.payload; 79 | } 80 | return user; 81 | }); 82 | }); 83 | 84 | /* 85 | * deleteUser Cases 86 | */ 87 | 88 | builder.addCase(deleteUser.pending, (state) => { 89 | state.loading = true; 90 | }); 91 | builder.addCase(deleteUser.rejected, (state, action) => { 92 | state.loading = false; 93 | state.error = action.error.message || "Something went wrong"; 94 | }); 95 | builder.addCase(deleteUser.fulfilled, (state, action) => { 96 | state.loading = true; 97 | state.users = state.users.filter((user) => user.id !== action.payload.id); 98 | }); 99 | 100 | /* 101 | * findUserById Cases 102 | */ 103 | 104 | builder.addCase(findUserById.pending, (state) => { 105 | state.loading = true; 106 | }); 107 | builder.addCase(findUserById.rejected, (state, action) => { 108 | state.loading = false; 109 | state.error = action.error.message || "Something went wrong"; 110 | }); 111 | builder.addCase(findUserById.fulfilled, (state, action) => { 112 | state.selectedUser = action.payload.length ? action.payload[0] : null; 113 | state.loading = false; 114 | }); 115 | 116 | /* 117 | * fetchUsers Cases 118 | */ 119 | 120 | builder.addCase(fetchUsers.pending, (state) => { 121 | state.loading = true; 122 | }); 123 | builder.addCase(fetchUsers.fulfilled, (state, action) => { 124 | state.loading = false; 125 | state.users = action.payload; 126 | }); 127 | builder.addCase(fetchUsers.rejected, (state) => { 128 | state.loading = false; 129 | }); 130 | }, 131 | reducers: { 132 | sortUsersByName: (state, action) => { 133 | if (action.payload === "asc") { 134 | state.users = state.users.sort((a, b) => a.name.localeCompare(b.name)); 135 | } else if (action.payload === "desc") { 136 | state.users = state.users.sort((a, b) => b.name.localeCompare(a.name)); 137 | } 138 | }, 139 | }, 140 | }); 141 | 142 | export default userSlice.reducer; 143 | 144 | export { findUserById, addUser, updateUser, deleteUser, fetchUsers }; 145 | -------------------------------------------------------------------------------- /src/store/slices/user.test.js: -------------------------------------------------------------------------------- 1 | import reducer, { 2 | initialState, 3 | findUserById, 4 | fetchUsers, 5 | addUser, 6 | updateUser, 7 | deleteUser, 8 | } from "./user"; 9 | import { 10 | mockNetWorkResponse, 11 | userId, 12 | getUserResponse, 13 | getUserListResponse, 14 | getCreateUserResponse, 15 | getUserUpdateResponse, 16 | } from "../../utils/tests.data"; 17 | import { store } from "../"; 18 | 19 | /** 20 | * Testing the initial state 21 | */ 22 | 23 | test("Should return initial state", () => { 24 | expect( 25 | reducer(undefined, { 26 | type: undefined, 27 | }) 28 | ).toEqual(initialState); 29 | }); 30 | 31 | /** 32 | * Testing the findUserById thunk 33 | */ 34 | 35 | describe("User List state tests", () => { 36 | beforeAll(() => { 37 | mockNetWorkResponse(); 38 | }); 39 | 40 | it("Should be able to fetch the user object", async () => { 41 | const result = await store.dispatch(findUserById(userId)); 42 | const user = result.payload; 43 | 44 | expect(result.type).toBe("users/findUserById/fulfilled"); 45 | expect(user).toEqual([getUserResponse]); 46 | 47 | const state = store.getState().users; 48 | 49 | expect(state.loading).toBe(false); 50 | expect(state.selectedUser).toEqual(getUserResponse); 51 | }); 52 | }); 53 | 54 | /** 55 | * Testing the fetchUsers thunk 56 | */ 57 | 58 | describe("List all users", () => { 59 | beforeAll(() => { 60 | mockNetWorkResponse(); 61 | }); 62 | 63 | it("Shoudl be able to fetch the user list", async () => { 64 | const result = await store.dispatch(fetchUsers()); 65 | 66 | const users = result.payload; 67 | 68 | expect(result.type).toBe("users/fetchUsers/fulfilled"); 69 | expect(users).toEqual(getUserListResponse); 70 | 71 | const state = store.getState().users; 72 | 73 | expect(state.users).toEqual(getUserListResponse); 74 | }); 75 | }); 76 | 77 | /** 78 | * Testing the createUser thunk 79 | */ 80 | 81 | describe("Create a new user", () => { 82 | beforeAll(() => { 83 | mockNetWorkResponse(); 84 | }); 85 | 86 | it("Should be able to create a new user", async () => { 87 | // Saving previous state 88 | const previousState = store.getState().users; 89 | 90 | const previousUsers = [...previousState.users]; 91 | previousUsers.push(getCreateUserResponse); 92 | 93 | // Dispatching the action 94 | 95 | const result = await store.dispatch(addUser(getCreateUserResponse)); 96 | 97 | const user = result.payload; 98 | 99 | expect(result.type).toBe("users/addUser/fulfilled"); 100 | expect(user).toEqual(getCreateUserResponse); 101 | 102 | const state = store.getState().users; 103 | 104 | expect(state.users).toEqual(previousUsers); 105 | }); 106 | }); 107 | 108 | /** 109 | * Testing the updateUser thunk 110 | */ 111 | 112 | describe("Update a user", () => { 113 | beforeAll(() => { 114 | mockNetWorkResponse(); 115 | }); 116 | 117 | it("Should be able to update a user", async () => { 118 | // Saving previous user 119 | const previousUserState = await store.dispatch(findUserById(userId)); 120 | 121 | const previousUser = previousUserState.payload; 122 | 123 | expect(previousUserState.type).toBe("users/findUserById/fulfilled"); 124 | 125 | // Dispatching the action 126 | 127 | const result = await store.dispatch(updateUser(getUserUpdateResponse)); 128 | const user = result.payload; 129 | 130 | expect(result.type).toBe("users/updateUser/fulfilled"); 131 | 132 | expect(user).toEqual(getUserUpdateResponse); 133 | expect(user).not.toEqual(previousUser); 134 | }); 135 | }); 136 | 137 | /** 138 | * Testing the deleteUser thunk 139 | */ 140 | 141 | describe("Delete a user", () => { 142 | beforeAll(() => { 143 | mockNetWorkResponse(); 144 | }); 145 | 146 | it("Should be able to delete a user", async () => { 147 | // Saving previous state 148 | const previousState = store.getState().users; 149 | 150 | const previousUsers = [...previousState.users]; 151 | 152 | // Dispatching the action 153 | 154 | const result = await store.dispatch(deleteUser(getUserResponse)); 155 | 156 | const user = result.payload; 157 | 158 | expect(result.type).toBe("users/deleteUser/fulfilled"); 159 | expect(user).toEqual(getUserResponse); 160 | 161 | const state = store.getState().users; 162 | 163 | expect(state.users).not.toEqual(previousUsers); 164 | expect(state.users).toEqual( 165 | previousUsers.filter((user) => user.id !== getUserResponse.id) 166 | ); 167 | }); 168 | }); 169 | -------------------------------------------------------------------------------- /src/utils/tests.data.js: -------------------------------------------------------------------------------- 1 | import axios from "axios"; 2 | import MockAdapter from "axios-mock-adapter"; 3 | 4 | const userId = 1; 5 | 6 | const getUserResponse = { 7 | id: 1, 8 | name: "Leanne Graham", 9 | username: "Bret", 10 | email: "Sincere@april.biz" 11 | }; 12 | 13 | const getUserUpdateResponse = { 14 | id: 1, 15 | name: "John Graham", 16 | username: "Bret", 17 | email: "Sincere@april.biz" 18 | }; 19 | 20 | const getCreateUserResponse = { 21 | id: 3, 22 | name: "Clementine Bauch", 23 | username: "Samantha", 24 | email: "Nathan@yesenia.net" 25 | }; 26 | 27 | const getUserListResponse = [ 28 | { 29 | id: 1, 30 | name: "Leanne Graham", 31 | username: "Bret", 32 | email: "Sincere@april.biz" 33 | }, 34 | { 35 | id: 2, 36 | name: "Ervin Howell", 37 | username: "Antonette", 38 | email: "ervin@april.biz" 39 | }, 40 | ]; 41 | 42 | // Adding mock network response that is used in tests 43 | 44 | const mockNetWorkResponse = () => { 45 | const mock = new MockAdapter(axios); 46 | mock.onGet(`/users/?id=${userId}`).reply(200, [getUserResponse]); 47 | mock.onGet(`/users/`).reply(200, getUserListResponse); 48 | mock.onPost(`/users/`).reply(200, getCreateUserResponse); 49 | mock.onPut(`/users/${userId}`).reply(200, getUserUpdateResponse); 50 | mock.onDelete(`/users/${userId}`).reply(200); 51 | }; 52 | 53 | export { 54 | mockNetWorkResponse, 55 | getUserResponse, 56 | getUserUpdateResponse, 57 | getCreateUserResponse, 58 | getUserListResponse, 59 | userId, 60 | }; --------------------------------------------------------------------------------