├── .gitignore
├── .prettierrc
├── README.md
├── __mocks__
├── axios.js
└── react-router-dom.js
├── package.json
├── public
├── favicon.ico
├── ice-cream-images
│ ├── ice-cream-0.svg
│ ├── ice-cream-1.svg
│ ├── ice-cream-10.svg
│ ├── ice-cream-11.svg
│ ├── ice-cream-12.svg
│ ├── ice-cream-13.svg
│ ├── ice-cream-14.svg
│ ├── ice-cream-15.svg
│ ├── ice-cream-16.svg
│ ├── ice-cream-17.svg
│ ├── ice-cream-18.svg
│ ├── ice-cream-19.svg
│ ├── ice-cream-2.svg
│ ├── ice-cream-20.svg
│ ├── ice-cream-21.svg
│ ├── ice-cream-22.svg
│ ├── ice-cream-23.svg
│ ├── ice-cream-24.svg
│ ├── ice-cream-25.svg
│ ├── ice-cream-26.svg
│ ├── ice-cream-27.svg
│ ├── ice-cream-28.svg
│ ├── ice-cream-3.svg
│ ├── ice-cream-4.svg
│ ├── ice-cream-5.svg
│ ├── ice-cream-6.svg
│ ├── ice-cream-7.svg
│ ├── ice-cream-8.svg
│ └── ice-cream-9.svg
├── index.html
└── manifest.json
├── server
└── index.js
├── src
├── App.js
├── __tests__
│ ├── __snapshots__
│ │ └── app.spec.js.snap
│ └── app.spec.js
├── assets
│ ├── css
│ │ └── style.css
│ ├── fonts
│ │ ├── cornerstone.woff
│ │ ├── cornerstone.woff2
│ │ ├── geomanist
│ │ │ ├── geomanist-book.eot
│ │ │ ├── geomanist-book.svg
│ │ │ ├── geomanist-book.ttf
│ │ │ ├── geomanist-book.woff
│ │ │ ├── geomanist-book.woff2
│ │ │ ├── geomanist-medium.eot
│ │ │ ├── geomanist-medium.svg
│ │ │ ├── geomanist-medium.ttf
│ │ │ ├── geomanist-medium.woff
│ │ │ ├── geomanist-medium.woff2
│ │ │ ├── geomanist-regular.eot
│ │ │ ├── geomanist-regular.svg
│ │ │ ├── geomanist-regular.ttf
│ │ │ ├── geomanist-regular.woff
│ │ │ └── geomanist-regular.woff2
│ │ └── kathen
│ │ │ └── kathen.otf
│ └── img
│ │ └── ultimate-ice-cream.svg
├── data
│ ├── __mocks__
│ │ └── iceCreamData.js
│ ├── __tests__
│ │ └── iceCreamData.spec.js
│ └── iceCreamData.js
├── hooks
│ ├── useUniqueIds.js
│ └── useValidation.js
├── ice-cream
│ ├── AddIceCream.js
│ ├── EditIceCream.js
│ ├── ErrorContainer.js
│ ├── IceCream.js
│ ├── IceCreamCard.js
│ ├── IceCreamCardContainer.js
│ ├── IceCreamImage.js
│ ├── IceCreams.js
│ ├── Menu.js
│ ├── __mocks__
│ │ ├── IceCream.js
│ │ └── IceCreamImage.js
│ └── __tests__
│ │ ├── AddIceCream.spec.js
│ │ ├── EditIceCream.spec.js
│ │ ├── IceCream.spec.js
│ │ ├── IceCreamCard.spec.js
│ │ ├── IceCreamCardContainer.spec.js
│ │ ├── IceCreamImage.spec.js
│ │ ├── IceCreams.spec.js
│ │ ├── Menu.spec.js
│ │ └── __snapshots__
│ │ └── IceCreamImage.spec.js.snap
├── index.js
├── setupTests.js
├── structure
│ ├── FocusLink.js
│ ├── Footer.js
│ ├── Header.js
│ ├── LoaderMessage.js
│ ├── Main.js
│ ├── __mocks__
│ │ ├── FocusLink.js
│ │ ├── LoaderMessage.js
│ │ └── Main.js
│ └── __tests__
│ │ ├── FocusLink.spec.js
│ │ ├── Footer.spec.js
│ │ ├── Header.spec.js
│ │ ├── LoaderMessage.spec.js
│ │ ├── Main.spec.js
│ │ └── __snapshots__
│ │ ├── FocusLink.spec.js.snap
│ │ ├── Footer.spec.js.snap
│ │ ├── Header.spec.js.snap
│ │ └── Main.spec.js.snap
└── utils
│ ├── __tests__
│ └── validators.spec.js
│ └── validators.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 | .idea
21 |
22 | npm-debug.log*
23 | yarn-debug.log*
24 | yarn-error.log*
25 |
--------------------------------------------------------------------------------
/.prettierrc:
--------------------------------------------------------------------------------
1 | {
2 | "singleQuote": true,
3 | "trailingComma": "es5"
4 | }
5 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
2 |
3 | ## Available Scripts
4 |
5 | In the project directory, you can run:
6 |
7 | ### `npm start`
8 |
9 | Runs the app in the development mode.
10 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
11 |
12 | The page will reload if you make edits.
13 | You will also see any lint errors in the console.
14 |
15 | ### `npm test`
16 |
17 | Launches the test runner in the interactive watch mode.
18 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
19 |
20 | ### `npm run build`
21 |
22 | Builds the app for production to the `build` folder.
23 | It correctly bundles React in production mode and optimizes the build for the best performance.
24 |
25 | The build is minified and the filenames include the hashes.
26 | Your app is ready to be deployed!
27 |
28 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
29 |
30 | ### `npm run eject`
31 |
32 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!**
33 |
34 | 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.
35 |
36 | 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.
37 |
38 | 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.
39 |
40 | ## Learn More
41 |
42 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
43 |
44 | To learn React, check out the [React documentation](https://reactjs.org/).
45 |
46 | ### Code Splitting
47 |
48 | This section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting
49 |
50 | ### Analyzing the Bundle Size
51 |
52 | This section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size
53 |
54 | ### Making a Progressive Web App
55 |
56 | This section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app
57 |
58 | ### Advanced Configuration
59 |
60 | This section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration
61 |
62 | ### Deployment
63 |
64 | This section has moved here: https://facebook.github.io/create-react-app/docs/deployment
65 |
66 | ### `npm run build` fails to minify
67 |
68 | This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify
69 |
--------------------------------------------------------------------------------
/__mocks__/axios.js:
--------------------------------------------------------------------------------
1 | export default {
2 | get: jest.fn(() => Promise.resolve({ data: {} })),
3 | post: jest.fn(() => Promise.resolve({ data: {} })),
4 | put: jest.fn(() => Promise.resolve({ data: {} })),
5 | delete: jest.fn(() => Promise.resolve()),
6 | };
7 |
--------------------------------------------------------------------------------
/__mocks__/react-router-dom.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 |
3 | export const Link = ({ children, to }) =>
4 | typeof to === 'string' ? (
5 | {children}
6 | ) : (
7 |
8 | {children}
9 | {to.state && {JSON.stringify(to.state)}}
10 | Link
11 |
12 | );
13 |
14 | export const NavLink = ({ children, to }) =>
15 | typeof to === 'string' ? (
16 | {children}
17 | ) : (
18 |
19 | {children}
20 | {to.state && {JSON.stringify(to.state)}}
21 | NavLink
22 |
23 | );
24 |
25 | export const withRouter = component => component;
26 |
27 | export const Switch =({children}) =>
{children}
;
28 |
29 | export const Route = ({path, component}) => {
30 | return <>{component.name}{path}>
31 | }
32 |
33 | export const Redirect = ({to}) => Redirect to {to};
34 |
35 | export const BrowserRouter = ({children}) => {children}
36 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "proxy": "http://localhost:5000",
3 | "name": "ultimate-react-icecream",
4 | "version": "0.1.0",
5 | "private": true,
6 | "dependencies": {
7 | "@emotion/core": "^10.0.10",
8 | "axios": "^0.18.0",
9 | "body-parser": "^1.19.0",
10 | "emotion": "^10.0.9",
11 | "express": "^4.16.4",
12 | "prettier": "^1.17.0",
13 | "prop-types": "^15.7.2",
14 | "react": "^16.8.6",
15 | "react-dom": "^16.8.6",
16 | "react-helmet": "^5.2.1",
17 | "react-router-dom": "^5.0.0",
18 | "react-scripts": "3.0.1",
19 | "uniqid": "^5.0.3"
20 | },
21 | "devDependencies": {
22 | "jest-dom": "^3.2.2",
23 | "jest-emotion": "^10.0.11",
24 | "@testing-library/react": "^8.0.1"
25 | },
26 | "scripts": {
27 | "start": "react-scripts start",
28 | "build": "react-scripts build",
29 | "test": "react-scripts test",
30 | "eject": "react-scripts eject",
31 | "start-server": "node ./server/index.js",
32 | "format": "prettier --write src/**/*.{js,scss}"
33 | },
34 | "eslintConfig": {
35 | "extends": "react-app"
36 | },
37 | "jest": {
38 | "collectCoverageFrom": [
39 | "src/**/*.{js,jsx}",
40 | "!src/index.js"
41 | ],
42 | "snapshotSerializers": [
43 | "jest-emotion"
44 | ]
45 | },
46 | "browserslist": {
47 | "production": [
48 | ">0.2%",
49 | "not dead",
50 | "not op_mini all"
51 | ],
52 | "development": [
53 | "last 1 chrome version",
54 | "last 1 firefox version",
55 | "last 1 safari version"
56 | ]
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/public/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ultimatecourses/ultimate-react-icecream/bc4aadef58841f087d74996955a9342e124b9a80/public/favicon.ico
--------------------------------------------------------------------------------
/public/ice-cream-images/ice-cream-0.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
64 |
--------------------------------------------------------------------------------
/public/ice-cream-images/ice-cream-1.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
71 |
--------------------------------------------------------------------------------
/public/ice-cream-images/ice-cream-10.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
79 |
--------------------------------------------------------------------------------
/public/ice-cream-images/ice-cream-11.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
132 |
--------------------------------------------------------------------------------
/public/ice-cream-images/ice-cream-14.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
66 |
--------------------------------------------------------------------------------
/public/ice-cream-images/ice-cream-18.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
89 |
--------------------------------------------------------------------------------
/public/ice-cream-images/ice-cream-19.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
103 |
--------------------------------------------------------------------------------
/public/ice-cream-images/ice-cream-2.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
111 |
--------------------------------------------------------------------------------
/public/ice-cream-images/ice-cream-20.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
79 |
--------------------------------------------------------------------------------
/public/ice-cream-images/ice-cream-22.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
102 |
--------------------------------------------------------------------------------
/public/ice-cream-images/ice-cream-23.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
116 |
--------------------------------------------------------------------------------
/public/ice-cream-images/ice-cream-24.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
112 |
--------------------------------------------------------------------------------
/public/ice-cream-images/ice-cream-3.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
58 |
--------------------------------------------------------------------------------
/public/ice-cream-images/ice-cream-4.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
94 |
--------------------------------------------------------------------------------
/public/ice-cream-images/ice-cream-5.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
68 |
--------------------------------------------------------------------------------
/public/ice-cream-images/ice-cream-6.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
89 |
--------------------------------------------------------------------------------
/public/ice-cream-images/ice-cream-7.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
75 |
--------------------------------------------------------------------------------
/public/ice-cream-images/ice-cream-8.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
114 |
--------------------------------------------------------------------------------
/public/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
12 |
13 |
22 | Ultimate Ice Cream
23 |
24 |
25 |
26 |
27 |
37 |
38 |
39 |
--------------------------------------------------------------------------------
/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 | "start_url": ".",
12 | "display": "standalone",
13 | "theme_color": "#000000",
14 | "background_color": "#ffffff"
15 | }
16 |
--------------------------------------------------------------------------------
/server/index.js:
--------------------------------------------------------------------------------
1 | const express = require('express');
2 | const bodyParser = require('body-parser');
3 | const app = express();
4 | app.use(bodyParser.json());
5 | const port = 5000;
6 |
7 | const iceCreams = [
8 | { id: 0, name: 'Stripey Madness' },
9 | { id: 1, name: 'Cherry Blast' },
10 | { id: 2, name: 'Cookie Tower of Power' },
11 | { id: 3, name: 'Inverted Stoplight' },
12 | { id: 4, name: 'Roswell Crash' },
13 | { id: 5, name: 'Arctic Rainbow' },
14 | { id: 6, name: 'Chocolate Hat' },
15 | { id: 7, name: 'Strawberry Jerry' },
16 | { id: 8, name: 'Mint Stack' },
17 | { id: 9, name: 'Cookie on a Stick' },
18 | { id: 10, name: 'Snowman Godfather' },
19 | { id: 11, name: 'Choco Mirror Ball' },
20 | { id: 12, name: 'Hearty Treat' },
21 | { id: 13, name: 'Strawberry Valentine' },
22 | { id: 14, name: "Stick 'o Lime" },
23 | { id: 15, name: 'Catastrophe' },
24 | { id: 16, name: 'Purple People Eater' },
25 | { id: 17, name: 'Strawberry Pine Tree' },
26 | { id: 18, name: 'It Blue My Mind' },
27 | { id: 19, name: 'Pistachio Satellite' },
28 | { id: 20, name: 'I Come in Peace' },
29 | { id: 21, name: 'Castle in the Sky' },
30 | { id: 22, name: 'Young Faithful' },
31 | { id: 23, name: 'Old Faithful' },
32 | { id: 24, name: 'Raspberry Pi' },
33 | { id: 25, name: 'Powerball' },
34 | { id: 26, name: 'Shaken and Whipped' },
35 | { id: 27, name: 'Sundae Everyday' },
36 | { id: 28, name: 'Toxic Sludge' },
37 | ];
38 |
39 | let menuData = [
40 | {
41 | id: 1,
42 | iceCream: { id: 1, name: 'Cherry Blast' },
43 | inStock: true,
44 | quantity: 20,
45 | price: 1.51,
46 | description:
47 | 'Blast your taste buds into fruity space with this vanilla and cherry bomb',
48 | },
49 | {
50 | id: 2,
51 | iceCream: { id: 15, name: 'Catastrophe' },
52 | inStock: true,
53 | quantity: 30,
54 | price: 1.64,
55 | description: 'A feline strawberry cranium, what could possibly go wrong?',
56 | },
57 | {
58 | id: 3,
59 | iceCream: { id: 10, name: 'Snowman Godfather' },
60 | inStock: true,
61 | quantity: 30,
62 | price: 1.5,
63 | description: "You'll lose your head over this inverted whisky-vanilla cone",
64 | },
65 | {
66 | id: 4,
67 | iceCream: { id: 4, name: 'Roswell Crash' },
68 | inStock: true,
69 | quantity: 10,
70 | price: 1.82,
71 | description: 'A zing of lime straight from Area 51',
72 | },
73 | {
74 | id: 5,
75 | iceCream: { id: 27, name: 'Sundae Everyday' },
76 | inStock: false,
77 | quantity: 0,
78 | price: 2.98,
79 | description: 'Hazelnut and vanilla, chocolate and cherries',
80 | },
81 | {
82 | id: 6,
83 | iceCream: { id: 21, name: 'Castle in the Sky' },
84 | inStock: true,
85 | quantity: 50,
86 | price: 2.19,
87 | description: 'A floating stronghold of vanilla, chocolate and pistachio',
88 | },
89 | {
90 | id: 7,
91 | iceCream: { id: 24, name: 'Raspberry Pi' },
92 | inStock: true,
93 | quantity: 20,
94 | price: 1.29,
95 | description: 'Chocolate electricity on a motherboard of raspberry',
96 | },
97 | ];
98 |
99 | const getAvailableStock = () =>
100 | iceCreams.filter(
101 | iceCream =>
102 | menuData.find(menuItem => menuItem.iceCream.id === iceCream.id) ===
103 | undefined
104 | );
105 |
106 | app.get('/api/menu/stock-ice-creams', (req, res) => {
107 | res.send(getAvailableStock());
108 | });
109 |
110 | app.get('/api/menu/stock-ice-creams/:id', (req, res) => {
111 | const iceCream = getAvailableStock().find(
112 | iceCream => iceCream.id === parseInt(req.params.id, 10)
113 | );
114 | if (iceCream) {
115 | res.send(iceCream);
116 | } else {
117 | res.status(404);
118 | res.send({ error: 'Ice cream not found' });
119 | }
120 | });
121 |
122 | app.get('/api/menu', (req, res) => {
123 | res.send(menuData);
124 | });
125 |
126 | app.post('/api/menu', (req, res) => {
127 | const { iceCream, ...rest } = req.body;
128 | const newMenuItem = {
129 | id: menuData.reduce((prev, cur) => (cur.id > prev ? cur.id : prev), 0) + 1,
130 | iceCream: {
131 | ...iceCreams.find(item => item.id === parseInt(iceCream.id, 10)),
132 | },
133 | ...rest,
134 | };
135 | menuData.push(newMenuItem);
136 |
137 | res.send(newMenuItem);
138 | });
139 |
140 | app.get('/api/menu/:id', (req, res) => {
141 | const menuItem = menuData.find(
142 | item => item.id === parseInt(req.params.id),
143 | 10
144 | );
145 | if (menuItem) {
146 | res.send(menuItem);
147 | } else {
148 | res.status(404);
149 | res.send('Menu item does not exist');
150 | }
151 | });
152 |
153 | app.put('/api/menu/:id', (req, res) => {
154 | const intId = parseInt(req.params.id, 10);
155 | const { iceCream, ...rest } = req.body;
156 |
157 | const updatedItem = {
158 | id: intId,
159 | iceCream: {
160 | ...iceCreams.find(item => item.id === parseInt(iceCream.id, 10)),
161 | },
162 | ...rest,
163 | };
164 | menuData = menuData.map(menuItem => {
165 | if (menuItem.id === parseInt(req.params.id, 10)) {
166 | return updatedItem;
167 | }
168 | return menuItem;
169 | });
170 |
171 | res.send(updatedItem);
172 | });
173 |
174 | app.delete('/api/menu/:id', (req, res) => {
175 | menuData = menuData.filter(
176 | menuItem => menuItem.id !== parseInt(req.params.id, 10)
177 | );
178 | res.status(204);
179 | res.send();
180 | });
181 |
182 | app.listen(port, () =>
183 | console.log(`Project ICE server listening on port ${port}!`)
184 | );
185 |
--------------------------------------------------------------------------------
/src/App.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import {
3 | BrowserRouter as Router,
4 | Route,
5 | Switch,
6 | Redirect,
7 | } from 'react-router-dom';
8 | import geomanistBookWoff from './assets/fonts/geomanist/geomanist-book.woff';
9 | import geomanistBookWoff2 from './assets/fonts/geomanist/geomanist-book.woff2';
10 | import cornerstoneWoff from './assets/fonts/cornerstone.woff';
11 | import cornerstoneWoff2 from './assets/fonts/cornerstone.woff2';
12 | import { Global, css } from '@emotion/core';
13 | import Header from './structure/Header';
14 | import Footer from './structure/Footer';
15 | import Menu from './ice-cream/Menu';
16 | import IceCreams from './ice-cream/IceCreams';
17 | import EditIceCream from './ice-cream/EditIceCream';
18 | import AddIceCream from './ice-cream/AddIceCream';
19 |
20 | const globalStyle = css`
21 | @font-face {
22 | font-family: 'geomanist';
23 | src: url(${geomanistBookWoff2}) format('woff2'),
24 | url(${geomanistBookWoff}) format('woff');
25 | font-weight: 400;
26 | font-style: normal;
27 | }
28 |
29 | @font-face {
30 | font-family: 'cornerstone';
31 | src: url(${cornerstoneWoff2}) format('woff2'),
32 | url(${cornerstoneWoff}) format('woff');
33 | font-weight: 400;
34 | font-style: normal;
35 | }
36 |
37 | *,
38 | *:before,
39 | *:after {
40 | box-sizing: border-box;
41 | -webkit-box-sizing: border-box;
42 | -moz-box-sizing: border-box;
43 | }
44 |
45 | html,
46 | body {
47 | height: 100%;
48 | width: 100%;
49 | margin: 0;
50 | padding: 0;
51 | color: #333;
52 | background: #ff71ba;
53 | font-family: 'geomanist', sans-serif;
54 | -webkit-font-smoothing: antialiased;
55 | -moz-osx-font-smoothing: grayscale;
56 | display: flex;
57 | }
58 |
59 | #root {
60 | width: 100%;
61 | }
62 |
63 | a {
64 | &:hover {
65 | text-decoration: none;
66 | }
67 | }
68 |
69 | h1,
70 | h2,
71 | h3,
72 | h4,
73 | h5 {
74 | font-weight: normal;
75 | padding: 0;
76 | margin: 0;
77 | }
78 |
79 | h3 {
80 | font-size: 24px;
81 | }
82 | h4 {
83 | font-size: 20px;
84 | }
85 |
86 | .visually-hidden:not(:focus):not(:active) {
87 | clip: rect(0 0 0 0);
88 | clip-path: inset(100%);
89 | height: 1px;
90 | overflow: hidden;
91 | position: absolute;
92 | white-space: nowrap;
93 | width: 1px;
94 | }
95 |
96 | .skip-link {
97 | padding: 6px;
98 | position: absolute;
99 | top: -40px;
100 | left: 0px;
101 | color: white;
102 | border-right: 1px solid white;
103 | border-bottom: 1px solid white;
104 | border-bottom-right-radius: 8px;
105 | background: #5c4268;
106 | transition: top 1s ease-out;
107 | z-index: 100;
108 |
109 | &:focus {
110 | position: absolute;
111 | left: 0px;
112 | top: 0px;
113 | outline-color: transparent;
114 | transition: top 0.1s ease-in;
115 | }
116 | }
117 | `;
118 |
119 | const App = () => {
120 | return (
121 |
122 |
123 |
124 | Skip to content
125 |
126 |
127 |
128 |
129 |
130 |
131 |
132 |
133 |
134 |
135 |
136 | );
137 | };
138 |
139 | export default App;
140 |
--------------------------------------------------------------------------------
/src/__tests__/__snapshots__/app.spec.js.snap:
--------------------------------------------------------------------------------
1 | // Jest Snapshot v1, https://goo.gl/fbAQLP
2 |
3 | exports[`App should render the app root 1`] = `
4 |
7 |
11 | Skip to content
12 |
13 |
14 | Header
15 |
16 |
19 |
20 | Menu
21 |
22 |
23 | /
24 |
25 |
26 | IceCreams
27 |
28 |
29 | /ice-creams
30 |
31 |
32 | AddIceCream
33 |
34 |
35 | /menu-items/add
36 |
37 |
38 | EditIceCream
39 |
40 |
41 | /menu-items/:menuItemId
42 |
43 |
44 | Redirect to
45 | /
46 |
47 |
48 |
49 | Footer
50 |
51 |
52 | `;
53 |
--------------------------------------------------------------------------------
/src/__tests__/app.spec.js:
--------------------------------------------------------------------------------
1 | jest.mock('../structure/Header', () => () => Header);
2 | jest.mock('../structure/Footer', () => () => Footer);
3 |
4 | import React from 'react';
5 | import { render, cleanup } from '@testing-library/react';
6 | import App from '../App';
7 |
8 | describe('App', () => {
9 | afterEach(cleanup);
10 |
11 | it('should render the app root', () => {
12 | const { container } = render();
13 | expect(container.firstChild).toMatchSnapshot();
14 | });
15 | });
16 |
--------------------------------------------------------------------------------
/src/assets/css/style.css:
--------------------------------------------------------------------------------
1 | *,
2 | *:before,
3 | *:after {
4 | box-sizing: border-box;
5 | -webkit-box-sizing: border-box;
6 | -moz-box-sizing: border-box;
7 | }
8 | html,
9 | body {
10 | height: 100%;
11 | width: 100%;
12 | margin: 0;
13 | padding: 0;
14 | color: #333;
15 | background: #23292d;
16 | -webkit-font-smoothing: antialiased;
17 | font: 300 16px/1.4 -apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica,
18 | Arial, sans-serif;
19 | display: flex;
20 | }
21 | #root {
22 | width: 100%;
23 | }
24 | a {
25 | text-decoration: none;
26 | outline: 0;
27 | }
28 |
29 | h1,
30 | h2,
31 | h3,
32 | h4,
33 | h5 {
34 | font-weight: normal;
35 | margin: 0;
36 | padding: 0;
37 | font-family: 'cornerstone';
38 | }
39 |
40 | h3 {
41 | font-size: 24px;
42 | }
43 | h4 {
44 | font-size: 20px;
45 | }
46 |
47 | @font-face {
48 | font-family: 'cornerstone';
49 | src: url('../fonts/cornerstone.woff2') format('woff2'),
50 | url('../fonts/cornerstone.woff') format('woff');
51 | font-weight: normal;
52 | font-style: normal;
53 | }
54 |
55 | .btn {
56 | display: inline-block;
57 | padding: 10px 15px;
58 | margin: 0;
59 | outline: 0;
60 | border: 0;
61 | border-radius: 3px;
62 | font-size: 16px;
63 | font-family: 'cornerstone';
64 | cursor: pointer;
65 | transition: all 0.2s ease;
66 | }
67 | .btn__ok {
68 | background: #0f9675;
69 | color: #fff;
70 | }
71 | .btn__ok:hover {
72 | background: #0a7d61;
73 | }
74 | .btn__warning {
75 | background: #ab131c;
76 | color: #fff;
77 | }
78 | .btn__warning:hover {
79 | background: #880c14;
80 | }
81 |
--------------------------------------------------------------------------------
/src/assets/fonts/cornerstone.woff:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ultimatecourses/ultimate-react-icecream/bc4aadef58841f087d74996955a9342e124b9a80/src/assets/fonts/cornerstone.woff
--------------------------------------------------------------------------------
/src/assets/fonts/cornerstone.woff2:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ultimatecourses/ultimate-react-icecream/bc4aadef58841f087d74996955a9342e124b9a80/src/assets/fonts/cornerstone.woff2
--------------------------------------------------------------------------------
/src/assets/fonts/geomanist/geomanist-book.eot:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ultimatecourses/ultimate-react-icecream/bc4aadef58841f087d74996955a9342e124b9a80/src/assets/fonts/geomanist/geomanist-book.eot
--------------------------------------------------------------------------------
/src/assets/fonts/geomanist/geomanist-book.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ultimatecourses/ultimate-react-icecream/bc4aadef58841f087d74996955a9342e124b9a80/src/assets/fonts/geomanist/geomanist-book.ttf
--------------------------------------------------------------------------------
/src/assets/fonts/geomanist/geomanist-book.woff:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ultimatecourses/ultimate-react-icecream/bc4aadef58841f087d74996955a9342e124b9a80/src/assets/fonts/geomanist/geomanist-book.woff
--------------------------------------------------------------------------------
/src/assets/fonts/geomanist/geomanist-book.woff2:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ultimatecourses/ultimate-react-icecream/bc4aadef58841f087d74996955a9342e124b9a80/src/assets/fonts/geomanist/geomanist-book.woff2
--------------------------------------------------------------------------------
/src/assets/fonts/geomanist/geomanist-medium.eot:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ultimatecourses/ultimate-react-icecream/bc4aadef58841f087d74996955a9342e124b9a80/src/assets/fonts/geomanist/geomanist-medium.eot
--------------------------------------------------------------------------------
/src/assets/fonts/geomanist/geomanist-medium.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ultimatecourses/ultimate-react-icecream/bc4aadef58841f087d74996955a9342e124b9a80/src/assets/fonts/geomanist/geomanist-medium.ttf
--------------------------------------------------------------------------------
/src/assets/fonts/geomanist/geomanist-medium.woff:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ultimatecourses/ultimate-react-icecream/bc4aadef58841f087d74996955a9342e124b9a80/src/assets/fonts/geomanist/geomanist-medium.woff
--------------------------------------------------------------------------------
/src/assets/fonts/geomanist/geomanist-medium.woff2:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ultimatecourses/ultimate-react-icecream/bc4aadef58841f087d74996955a9342e124b9a80/src/assets/fonts/geomanist/geomanist-medium.woff2
--------------------------------------------------------------------------------
/src/assets/fonts/geomanist/geomanist-regular.eot:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ultimatecourses/ultimate-react-icecream/bc4aadef58841f087d74996955a9342e124b9a80/src/assets/fonts/geomanist/geomanist-regular.eot
--------------------------------------------------------------------------------
/src/assets/fonts/geomanist/geomanist-regular.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ultimatecourses/ultimate-react-icecream/bc4aadef58841f087d74996955a9342e124b9a80/src/assets/fonts/geomanist/geomanist-regular.ttf
--------------------------------------------------------------------------------
/src/assets/fonts/geomanist/geomanist-regular.woff:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ultimatecourses/ultimate-react-icecream/bc4aadef58841f087d74996955a9342e124b9a80/src/assets/fonts/geomanist/geomanist-regular.woff
--------------------------------------------------------------------------------
/src/assets/fonts/geomanist/geomanist-regular.woff2:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ultimatecourses/ultimate-react-icecream/bc4aadef58841f087d74996955a9342e124b9a80/src/assets/fonts/geomanist/geomanist-regular.woff2
--------------------------------------------------------------------------------
/src/assets/fonts/kathen/kathen.otf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ultimatecourses/ultimate-react-icecream/bc4aadef58841f087d74996955a9342e124b9a80/src/assets/fonts/kathen/kathen.otf
--------------------------------------------------------------------------------
/src/data/__mocks__/iceCreamData.js:
--------------------------------------------------------------------------------
1 | export const getIceCreams = jest.fn(() => Promise.resolve({ data: {} }));
2 |
3 | export const getIceCream = jest.fn(() => Promise.resolve({ data: {} }));
4 |
5 | export const getMenu = jest.fn(() => Promise.resolve({ data: {} }));
6 |
7 | export const getMenuItem = jest.fn(() => Promise.resolve({ data: {} }));
8 |
9 | export const postMenuItem = jest.fn(() => Promise.resolve({ data: {} }));
10 |
11 | export const putMenuItem = jest.fn(() => Promise.resolve({ data: {} }));
12 |
13 | export const deleteMenuItem = jest.fn(() => Promise.resolve({ data: {} }));
14 |
--------------------------------------------------------------------------------
/src/data/__tests__/iceCreamData.spec.js:
--------------------------------------------------------------------------------
1 | import {
2 | getMenu,
3 | getIceCreams,
4 | deleteMenuItem,
5 | putMenuItem,
6 | postMenuItem,
7 | getIceCream,
8 | getMenuItem,
9 | } from '../iceCreamData';
10 | import axios from 'axios';
11 |
12 | afterEach(() => {
13 | axios.get.mockClear();
14 | axios.post.mockClear();
15 | axios.put.mockClear();
16 | axios.delete.mockClear();
17 | });
18 |
19 | describe('getMenu', () => {
20 | const mockMenuData = [
21 | {
22 | id: 5,
23 | iceCream: { id: 27, name: 'Sundae Everyday' },
24 | inStock: false,
25 | quantity: 0,
26 | price: 2.98,
27 | description: 'Hazelnut and vanilla, chocolate and cherries',
28 | },
29 | {
30 | id: 6,
31 | iceCream: { id: 21, name: 'Castle in the Sky' },
32 | inStock: true,
33 | quantity: 50,
34 | price: 2.19,
35 | description: 'A floating stronghold of vanilla, chocolate and pistachio',
36 | },
37 | {
38 | id: 10,
39 | iceCream: { id: 28, name: 'Castle in the Sky' },
40 | inStock: true,
41 | quantity: 20,
42 | price: 1.19,
43 | description:
44 | 'Another floating stronghold of vanilla, chocolate and pistachio',
45 | },
46 | {
47 | id: 7,
48 | iceCream: { id: 24, name: 'Raspberry Pi' },
49 | inStock: true,
50 | quantity: 20,
51 | price: 1.29,
52 | description: 'Chocolate electricity on a motherboard of raspberry',
53 | },
54 | ];
55 |
56 | it('should fetch and sort the menu data', async () => {
57 | axios.get.mockResolvedValueOnce({ data: mockMenuData });
58 |
59 | const data = await getMenu();
60 |
61 | expect(axios.get).toHaveBeenCalledWith('/api/menu');
62 |
63 | expect(data).toEqual([
64 | {
65 | description:
66 | 'A floating stronghold of vanilla, chocolate and pistachio',
67 | iceCream: { id: 21, name: 'Castle in the Sky' },
68 | id: 6,
69 | inStock: true,
70 | price: 2.19,
71 | quantity: 50,
72 | },
73 | {
74 | description:
75 | 'Another floating stronghold of vanilla, chocolate and pistachio',
76 | iceCream: { id: 28, name: 'Castle in the Sky' },
77 | id: 10,
78 | inStock: true,
79 | price: 1.19,
80 | quantity: 20,
81 | },
82 | {
83 | description: 'Chocolate electricity on a motherboard of raspberry',
84 | iceCream: { id: 24, name: 'Raspberry Pi' },
85 | id: 7,
86 | inStock: true,
87 | price: 1.29,
88 | quantity: 20,
89 | },
90 | {
91 | description: 'Hazelnut and vanilla, chocolate and cherries',
92 | iceCream: { id: 27, name: 'Sundae Everyday' },
93 | id: 5,
94 | inStock: false,
95 | price: 2.98,
96 | quantity: 0,
97 | },
98 | ]);
99 | });
100 | });
101 |
102 | describe('getIceCream', () => {
103 | it('should get an ice cream', async () => {
104 | axios.get.mockResolvedValueOnce({ data: { id: 13, name: 'yum' } });
105 |
106 | const iceCream = await getIceCream(13);
107 |
108 | expect(axios.get).toHaveBeenCalledWith('/api/menu/stock-ice-creams/13');
109 | expect(iceCream).toEqual({ id: 13, name: 'yum' });
110 | });
111 |
112 | it('should pass through api errors', async () => {
113 | let error = null;
114 |
115 | axios.get.mockRejectedValueOnce({ response: { status: 404 } });
116 |
117 | try {
118 | await getIceCream(13);
119 | } catch (e) {
120 | error = e;
121 | }
122 |
123 | expect(error).toEqual({ response: { status: 404 } });
124 | });
125 | });
126 |
127 | describe('getIceCreams', () => {
128 | const mockIceCreamsData = [
129 | { id: 4, name: 'Roswell Crash' },
130 | { id: 5, name: 'Arctic Rainbow' },
131 | { id: 6, name: 'Chocolate Hat' },
132 | { id: 7, name: 'Strawberry Jerry' },
133 | { id: 8, name: 'Chocolate Hat' },
134 | ];
135 |
136 | it('should fetch and sort the ice creams data', async () => {
137 | axios.get.mockResolvedValueOnce({ data: mockIceCreamsData });
138 |
139 | const data = await getIceCreams();
140 |
141 | expect(axios.get).toHaveBeenCalledWith('/api/menu/stock-ice-creams');
142 |
143 | expect(data).toEqual([
144 | { id: 5, name: 'Arctic Rainbow' },
145 | { id: 6, name: 'Chocolate Hat' },
146 | { id: 8, name: 'Chocolate Hat' },
147 | { id: 4, name: 'Roswell Crash' },
148 | { id: 7, name: 'Strawberry Jerry' },
149 | ]);
150 | });
151 | });
152 |
153 | describe('deleteMenuItem', () => {
154 | it('should delete a menu item', async () => {
155 | await deleteMenuItem(12);
156 |
157 | expect(axios.delete).toHaveBeenCalledWith('/api/menu/12');
158 | });
159 | });
160 |
161 | describe('getMenuItem', () => {
162 | it('should get a menu item', async () => {
163 | axios.get.mockResolvedValueOnce({ data: { id: 23, someField: 10 } });
164 |
165 | const menuItem = await getMenuItem(23);
166 |
167 | expect(axios.get).toHaveBeenCalledWith('/api/menu/23');
168 | expect(menuItem).toEqual({ id: 23, someField: 10 });
169 | });
170 |
171 | it('should pass through api errors', async () => {
172 | let error = null;
173 |
174 | axios.get.mockRejectedValueOnce({ response: { status: 404 } });
175 |
176 | try {
177 | await getMenuItem(23);
178 | } catch (e) {
179 | error = e;
180 | }
181 |
182 | expect(error).toEqual({ response: { status: 404 } });
183 | });
184 | });
185 |
186 | describe('putMenuItem', () => {
187 | it('should save an updated menu item', async () => {
188 | axios.put.mockResolvedValueOnce({ data: { id: 23, someOtherField: 10 } });
189 |
190 | const updated = await putMenuItem({ id: 23 });
191 |
192 | expect(axios.put).toHaveBeenCalledWith('/api/menu/23', { id: 23 });
193 | expect(updated).toEqual({ id: 23, someOtherField: 10 });
194 | });
195 |
196 | it('should pass through api errors', async () => {
197 | let error = null;
198 |
199 | axios.put.mockRejectedValueOnce({ response: { status: 404 } });
200 |
201 | try {
202 | await putMenuItem({ id: 23 });
203 | } catch (e) {
204 | error = e;
205 | }
206 |
207 | expect(error).toEqual({ response: { status: 404 } });
208 | });
209 | });
210 |
211 | describe('postMenuItem', () => {
212 | it('should save a new menu item', async () => {
213 | axios.post.mockResolvedValueOnce({ data: { id: 23, someField: 10 } });
214 |
215 | const posted = await postMenuItem({ someField: 10 });
216 |
217 | expect(axios.post).toHaveBeenCalledWith('/api/menu', { someField: 10 });
218 | expect(posted).toEqual({ id: 23, someField: 10 });
219 | });
220 |
221 | it('should pass through api errors', async () => {
222 | let error = null;
223 |
224 | axios.post.mockRejectedValueOnce({ response: { status: 409 } });
225 |
226 | try {
227 | await postMenuItem({ someField: 10 });
228 | } catch (e) {
229 | error = e;
230 | }
231 |
232 | expect(error).toEqual({ response: { status: 409 } });
233 | });
234 | });
235 |
--------------------------------------------------------------------------------
/src/data/iceCreamData.js:
--------------------------------------------------------------------------------
1 | import axios from 'axios';
2 |
3 | export const getIceCreams = () => {
4 | return axios.get('/api/menu/stock-ice-creams').then(response => {
5 | return response.data.sort((a, b) => {
6 | if (a.name < b.name) {
7 | return -1;
8 | }
9 | if (a.name > b.name) {
10 | return 1;
11 | }
12 | return 0;
13 | });
14 | });
15 | };
16 |
17 | export const getIceCream = id => {
18 | return axios
19 | .get(`/api/menu/stock-ice-creams/${id.toString()}`)
20 | .then(response => response.data)
21 | .catch(err => {
22 | throw err;
23 | });
24 | };
25 |
26 | export const getMenu = () => {
27 | return axios.get('/api/menu').then(response => {
28 | return response.data.sort((a, b) => {
29 | if (a.iceCream.name < b.iceCream.name) {
30 | return -1;
31 | }
32 | if (a.iceCream.name > b.iceCream.name) {
33 | return 1;
34 | }
35 | return 0;
36 | });
37 | });
38 | };
39 |
40 | export const getMenuItem = id => {
41 | return axios
42 | .get(`/api/menu/${id}`)
43 | .then(response => response.data)
44 | .catch(err => {
45 | throw err;
46 | });
47 | };
48 |
49 | export const postMenuItem = menuItem => {
50 | return axios
51 | .post('/api/menu', menuItem)
52 | .then(response => {
53 | return response.data;
54 | })
55 | .catch(err => {
56 | throw err;
57 | });
58 | };
59 |
60 | export const putMenuItem = menuItem => {
61 | return axios
62 | .put(`/api/menu/${menuItem.id.toString()}`, menuItem)
63 | .then(response => response.data)
64 | .catch(err => {
65 | throw err;
66 | });
67 | };
68 |
69 | export const deleteMenuItem = id => {
70 | return axios.delete(`/api/menu/${id.toString()}`);
71 | };
72 |
--------------------------------------------------------------------------------
/src/hooks/useUniqueIds.js:
--------------------------------------------------------------------------------
1 | import { useRef } from 'react';
2 | import uniqid from 'uniqid';
3 |
4 | const useUniqueIds = count => {
5 | const ids = useRef([...new Array(count)].map(() => uniqid()));
6 | return ids.current;
7 | };
8 |
9 | export default useUniqueIds;
10 |
--------------------------------------------------------------------------------
/src/hooks/useValidation.js:
--------------------------------------------------------------------------------
1 | import { useState, useEffect } from 'react';
2 |
3 | const useValidation = (
4 | value,
5 | errorId,
6 | showError,
7 | validatorFn,
8 | isRequired,
9 | compareValue = null
10 | ) => {
11 | const [error, setError] = useState('');
12 |
13 | useEffect(() => {
14 | setError(validatorFn(value, compareValue));
15 | }, [value, compareValue, validatorFn]);
16 |
17 | return [
18 | error,
19 | {
20 | 'aria-describedby': error && showError ? errorId : null,
21 | 'aria-invalid': error && showError ? 'true' : 'false',
22 | 'aria-required': isRequired ? 'true' : null,
23 | required: isRequired,
24 | },
25 | ];
26 | };
27 |
28 | export default useValidation;
29 |
--------------------------------------------------------------------------------
/src/ice-cream/AddIceCream.js:
--------------------------------------------------------------------------------
1 | import React, { useEffect, useState } from 'react';
2 | import Main from '../structure/Main';
3 | import LoaderMessage from '../structure/LoaderMessage';
4 | import IceCream from './IceCream';
5 | import { getIceCream, postMenuItem } from '../data/iceCreamData';
6 | import PropTypes from 'prop-types';
7 |
8 | const AddIceCream = ({ location, history }) => {
9 | const [isLoading, setIsLoading] = useState(true);
10 | const [iceCream, setIceCream] = useState({});
11 |
12 | useEffect(() => {
13 | let isMounted = true;
14 | getIceCream(location.search.split('=')[1])
15 | .then(iceCreamResponse => {
16 | if (isMounted) {
17 | setIceCream(iceCreamResponse);
18 | setIsLoading(false);
19 | }
20 | })
21 | .catch(err => {
22 | if (err.response.status === 404 && isMounted) {
23 | history.replace('/', { focus: true });
24 | }
25 | });
26 | return () => {
27 | isMounted = false;
28 | };
29 | }, [history, location.search]);
30 |
31 | const onSubmitHandler = menuItem => {
32 | postMenuItem(menuItem).then(() => {
33 | history.push('/', { focus: true });
34 | });
35 | };
36 |
37 | return (
38 |
39 |
44 | {!isLoading && (
45 |
46 | )}
47 |
48 | );
49 | };
50 |
51 | AddIceCream.propTypes = {
52 | location: PropTypes.shape({
53 | search: PropTypes.string.isRequired,
54 | }),
55 | history: PropTypes.shape({
56 | push: PropTypes.func.isRequired,
57 | replace: PropTypes.func.isRequired,
58 | }),
59 | };
60 |
61 | export default AddIceCream;
62 |
--------------------------------------------------------------------------------
/src/ice-cream/EditIceCream.js:
--------------------------------------------------------------------------------
1 | import React, { useState, useEffect } from 'react';
2 | import Main from '../structure/Main';
3 | import LoaderMessage from '../structure/LoaderMessage';
4 | import IceCream from './IceCream';
5 | import { getMenuItem, putMenuItem, deleteMenuItem } from '../data/iceCreamData';
6 | import PropTypes from 'prop-types';
7 |
8 | const EditIceCream = ({ match, history }) => {
9 | const [isLoading, setIsLoading] = useState(true);
10 | const [menuItem, setMenuItem] = useState({});
11 |
12 | useEffect(() => {
13 | let isMounted = true;
14 | getMenuItem(match.params.menuItemId)
15 | .then(item => {
16 | if (isMounted) {
17 | setMenuItem(item);
18 | setIsLoading(false);
19 | }
20 | })
21 | .catch(err => {
22 | if (err.response.status === 404 && isMounted) {
23 | history.replace('/', { focus: true });
24 | }
25 | });
26 | return () => {
27 | isMounted = false;
28 | };
29 | }, [match.params.menuItemId, history]);
30 |
31 | const onSubmitHandler = updatedItem => {
32 | putMenuItem({ id: menuItem.id, ...updatedItem }).then(() => {
33 | history.push('/', { focus: true });
34 | });
35 | };
36 |
37 | const onDeleteHandler = () => {
38 | deleteMenuItem(match.params.menuItemId).then(() => {
39 | history.replace('/', { focus: true });
40 | });
41 | };
42 |
43 | return (
44 |
45 |
50 | {!isLoading && (
51 |
56 | )}
57 |
58 | );
59 | };
60 |
61 | EditIceCream.propTypes = {
62 | match: PropTypes.shape({
63 | params: PropTypes.object.isRequired,
64 | }),
65 | history: PropTypes.shape({
66 | push: PropTypes.func.isRequired,
67 | replace: PropTypes.func.isRequired,
68 | }),
69 | };
70 |
71 | export default EditIceCream;
72 |
--------------------------------------------------------------------------------
/src/ice-cream/ErrorContainer.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import PropTypes from 'prop-types';
3 |
4 | const ErrorContainer = ({ children, errorText, hasSubmitted, errorId }) => (
5 |
6 | {children}
7 |
8 | {errorText && hasSubmitted && {errorText}}
9 |
10 |
11 | );
12 |
13 | ErrorContainer.propTypes = {
14 | children: PropTypes.node.isRequired,
15 | errorText: PropTypes.string,
16 | hasSubmitted: PropTypes.bool.isRequired,
17 | errorId: PropTypes.string.isRequired,
18 | };
19 |
20 | export default ErrorContainer;
21 |
--------------------------------------------------------------------------------
/src/ice-cream/IceCreamCard.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import FocusLink from '../structure/FocusLink';
3 | import IceCreamImage from './IceCreamImage';
4 | import { css } from 'emotion/macro';
5 | import PropTypes from 'prop-types';
6 |
7 | const cardStyle = css`
8 | position: relative;
9 | display: grid;
10 | grid-template-columns: 1fr;
11 | grid-auto-rows: max-content;
12 | height: 100%;
13 | align-items: center;
14 | background-color: #ffffff;
15 | border-radius: 1em;
16 | cursor: pointer;
17 | border: 1px solid rgba(32, 33, 36, 0.12);
18 | background-clip: padding-box;
19 |
20 | transform: translate(0) scale(1, 1);
21 | transition: all 0.2s ease-in-out;
22 |
23 | @media screen and (max-width: 600px) {
24 | grid-template-rows: 70% 30%;
25 | }
26 |
27 | &:hover,
28 | &:focus-within {
29 | transform: scale(1.02);
30 | transition: all 0.2s ease-in-out;
31 | }
32 |
33 | &:hover {
34 | .text-container {
35 | h3 {
36 | a {
37 | text-decoration: underline;
38 | }
39 | }
40 | }
41 | }
42 |
43 | &:focus-within {
44 | box-shadow: 0 0 0 3px #ff71ba, 0 0 0 6px rgba(0, 0, 0, 0.6);
45 |
46 | a {
47 | outline: 2px solid transparent;
48 | }
49 | }
50 |
51 | .text-container {
52 | display: grid;
53 | grid-template-columns: 1fr;
54 | grid-auto-rows: max-content;
55 | padding: 1.5em;
56 | height: 100%;
57 |
58 | h3 {
59 | padding: 0;
60 | color: #403147;
61 | font-size: 1.25em;
62 | line-height: 1.4375em;
63 |
64 | a {
65 | color: #403147;
66 | margin-bottom: 1.5em;
67 | text-decoration: none;
68 | }
69 | }
70 |
71 | .content {
72 | }
73 | }
74 |
75 | .image-container {
76 | display: flex;
77 | align-content: center;
78 | justify-content: center;
79 | background-color: #f8f8f8;
80 | text-align: center;
81 | border-top-right-radius: 1em;
82 | border-top-left-radius: 1em;
83 | padding-top: 3em;
84 | padding-bottom: 3em;
85 | height: 100%;
86 | border-bottom: 1px solid rgba(32, 33, 36, 0.1);
87 |
88 | img {
89 | max-width: 60%;
90 | }
91 | }
92 | `;
93 |
94 | export const IceCreamCard = ({
95 | iceCreamId,
96 | heading,
97 | to,
98 | history,
99 | children,
100 | }) => {
101 | const onItemClickHandler = () => {
102 | history.push(to);
103 | };
104 |
105 | const onLinkClickHandler = e => {
106 | //This is done to avoid the click handler of the
107 | //firing and placing two browse entries in browser history
108 | e.stopPropagation();
109 | };
110 |
111 | return (
112 | {
115 | onItemClickHandler();
116 | }}
117 | >
118 |
119 |
120 |
121 |
122 |
123 |
124 | {heading}
125 |
126 |
127 | {children &&
{children}
}
128 |
129 |
130 | );
131 | };
132 |
133 | IceCreamCard.propTypes = {
134 | iceCreamId: PropTypes.number.isRequired,
135 | heading: PropTypes.string.isRequired,
136 | to: PropTypes.oneOfType([
137 | PropTypes.string,
138 | PropTypes.shape({
139 | pathname: PropTypes.string.isRequired,
140 | }),
141 | ]).isRequired,
142 | history: PropTypes.shape({
143 | push: PropTypes.func.isRequired,
144 | }),
145 | children: PropTypes.node,
146 | };
147 |
148 | export default IceCreamCard;
149 |
--------------------------------------------------------------------------------
/src/ice-cream/IceCreamCardContainer.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { css } from 'emotion/macro';
3 | import PropTypes from 'prop-types';
4 |
5 | const containerStyle = css`
6 | display: grid;
7 | grid-template-columns: 1fr 1fr 1fr;
8 | grid-auto-rows: 1fr;
9 | grid-gap: 2em;
10 | list-style: none;
11 | padding: 0;
12 | margin: 0;
13 |
14 | @media screen and (max-width: 1000px) {
15 | grid-template-columns: 1fr 1fr;
16 | }
17 |
18 | @media screen and (max-width: 700px) {
19 | grid-template-columns: 1fr;
20 | }
21 | `;
22 |
23 | const IceCreamCardContainer = ({ children }) => (
24 |
25 | {React.Children.map(children, card => (
26 | - {card}
27 | ))}
28 |
29 | );
30 |
31 | IceCreamCardContainer.propTypes = {
32 | children: PropTypes.node.isRequired,
33 | };
34 |
35 | export default IceCreamCardContainer;
36 |
--------------------------------------------------------------------------------
/src/ice-cream/IceCreamImage.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import PropTypes from 'prop-types';
3 |
4 | const IceCreamImage = ({ iceCreamId }) => {
5 | return (
6 | iceCreamId !== null &&
7 | iceCreamId !== undefined && (
8 |
14 | )
15 | );
16 | };
17 |
18 | IceCreamImage.propTypes = {
19 | iceCreamId: PropTypes.number.isRequired,
20 | };
21 |
22 | export default IceCreamImage;
23 |
--------------------------------------------------------------------------------
/src/ice-cream/IceCreams.js:
--------------------------------------------------------------------------------
1 | import React, { useEffect, useState } from 'react';
2 | import Main from '../structure/Main';
3 | import LoaderMessage from '../structure/LoaderMessage';
4 | import IceCreamCard from './IceCreamCard';
5 | import IceCreamCardContainer from './IceCreamCardContainer';
6 | import { getIceCreams } from '../data/iceCreamData';
7 | import { css } from 'emotion/macro';
8 | import PropTypes from 'prop-types';
9 |
10 | const paragraphStyle = css`
11 | max-width: 60%;
12 | margin: 0 auto;
13 | padding-bottom: 3em;
14 | `;
15 |
16 | const IceCreams = ({ history }) => {
17 | const [isLoading, setIsLoading] = useState(true);
18 | const [iceCreams, setIceCreams] = useState([]);
19 |
20 | useEffect(() => {
21 | let isMounted = true;
22 | getIceCreams().then(iceCreams => {
23 | if (isMounted) {
24 | setIceCreams(iceCreams);
25 | setIsLoading(false);
26 | }
27 | });
28 | return () => {
29 | isMounted = false;
30 | };
31 | }, []);
32 |
33 | return (
34 |
35 |
40 | {iceCreams.length > 0 ? (
41 |
42 | {iceCreams.map(({ id, name }) => (
43 |
53 | ))}
54 |
55 | ) : (
56 | !isLoading && (
57 | Your menu is fully stocked!
58 | )
59 | )}
60 |
61 | );
62 | };
63 |
64 | IceCreams.propTypes = {
65 | history: PropTypes.shape({
66 | push: PropTypes.func.isRequired,
67 | }),
68 | };
69 |
70 | export default IceCreams;
71 |
--------------------------------------------------------------------------------
/src/ice-cream/Menu.js:
--------------------------------------------------------------------------------
1 | import React, { useState, useEffect } from 'react';
2 | import Main from '../structure/Main';
3 | import LoaderMessage from '../structure/LoaderMessage';
4 | import IceCreamCardContainer from './IceCreamCardContainer';
5 | import IceCreamCard from './IceCreamCard';
6 | import { getMenu } from '../data/iceCreamData';
7 | import { css } from 'emotion/macro';
8 | import PropTypes from 'prop-types';
9 |
10 | const cardContentStyle = css`
11 | display: flex;
12 | flex-direction: row;
13 | flex-wrap: wrap;
14 | padding: 0.3em 0 0 0;
15 |
16 | p {
17 | margin: 0;
18 | color: #403147;
19 | }
20 |
21 | p.price {
22 | font-size: 1em;
23 | position: relative;
24 | margin-right: 1.125em;
25 | color: rgba(64, 49, 71, 0.8);
26 |
27 | &:after {
28 | content: '';
29 | width: 4px;
30 | height: 4px;
31 | position: absolute;
32 | top: 50%;
33 | margin-top: -3px;
34 | right: -0.7em;
35 | background: rgba(64, 49, 71, 0.4);
36 | border-radius: 50%;
37 | }
38 | }
39 |
40 | p.stock {
41 | font-size: 1em;
42 | color: rgba(64, 49, 71, 0.8);
43 |
44 | &.out {
45 | color: #d8474f;
46 | }
47 | }
48 |
49 | p.description {
50 | width: 100%;
51 | margin-top: 1em;
52 | line-height: 1.375em;
53 | color: rgba(64, 49, 71, 0.9);
54 | font-size: 0.875em;
55 | }
56 | `;
57 |
58 | const Menu = ({ history }) => {
59 | const [menu, setMenu] = useState([]);
60 | const [isLoading, setIsLoading] = useState(true);
61 |
62 | useEffect(() => {
63 | let isMounted = true;
64 | getMenu().then(menuData => {
65 | if (isMounted) {
66 | setMenu(menuData);
67 | setIsLoading(false);
68 | }
69 | });
70 | return () => {
71 | isMounted = false;
72 | };
73 | }, []);
74 |
75 | return (
76 |
77 |
82 | {!isLoading && (
83 |
84 | {menu.length > 0 && !isLoading ? (
85 | <>
86 |
87 | {menu.map(
88 | ({ id, iceCream, price, description, inStock, quantity }) => (
89 |
96 |
97 |
{`$${price.toFixed(2)}`}
98 |
99 | {inStock
100 | ? `${quantity} in stock`
101 | : 'Currently out of stock!'}
102 |
103 |
{description}
104 |
105 |
106 | )
107 | )}
108 |
109 | >
110 | ) : (
111 |
Your menu is empty! The sadness!!
112 | )}
113 |
114 | )}
115 |
116 | );
117 | };
118 |
119 | Menu.propTypes = {
120 | history: PropTypes.shape({
121 | push: PropTypes.func.isRequired,
122 | }),
123 | };
124 |
125 | export default Menu;
126 |
--------------------------------------------------------------------------------
/src/ice-cream/__mocks__/IceCream.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 |
3 | const IceCream = ({ iceCream, onSubmit }) => (
4 |
5 | {iceCream.name}
6 |
12 | );
13 |
--------------------------------------------------------------------------------
/src/ice-cream/__mocks__/IceCreamImage.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 |
3 | const IceCreamImage = ({ iceCreamId }) => (
4 |
5 | );
6 |
7 | export default IceCreamImage;
8 |
--------------------------------------------------------------------------------
/src/ice-cream/__tests__/AddIceCream.spec.js:
--------------------------------------------------------------------------------
1 | jest.mock('../../structure/Main');
2 | jest.mock('../../structure/LoaderMessage');
3 | jest.mock('../IceCreamImage');
4 | jest.mock('../../data/iceCreamData');
5 |
6 | import React from 'react';
7 | import {
8 | render,
9 | waitForElement,
10 | wait,
11 | fireEvent,
12 | cleanup,
13 | } from '@testing-library/react';
14 | import AddIceCream from '../AddIceCream';
15 | import { getIceCream, postMenuItem } from '../../data/iceCreamData';
16 |
17 | describe('AddIceCream', () => {
18 | afterEach(cleanup);
19 |
20 | it('should render and load data', async () => {
21 | getIceCream.mockResolvedValueOnce({
22 | id: 3,
23 | name: 'Inverted Stoplight',
24 | });
25 |
26 | const mockLocation = { search: '?iceCreamId=5' };
27 | const mockHistory = { push: jest.fn(), replace: jest.fn() };
28 | const { container, getByTestId, getByAltText } = render(
29 |
30 | );
31 |
32 | const heading = await waitForElement(() =>
33 | container.firstChild.querySelector('h2')
34 | );
35 |
36 | expect(heading).toHaveTextContent('Add some goodness to the menu');
37 |
38 | expect(getByTestId('loaderMessage')).toHaveTextContent(
39 | 'Loading ice cream.-Ice cream loaded.'
40 | );
41 |
42 | expect(getByAltText('')).toHaveAttribute('src', 'ice-cream-3.svg');
43 |
44 | expect(container.firstChild.querySelector('dl dd')).toHaveTextContent(
45 | 'Inverted Stoplight'
46 | );
47 | });
48 |
49 | it('should safely unmount', async () => {
50 | const originalErrofn = global.console.error;
51 |
52 | getIceCream.mockResolvedValueOnce({
53 | id: 3,
54 | name: 'Inverted Stoplight',
55 | });
56 |
57 | const mockLocation = { search: '?iceCreamId=5' };
58 | const mockHistory = { push: jest.fn(), replace: jest.fn() };
59 | const { unmount } = render(
60 |
61 | );
62 | global.console.error = jest.fn();
63 | await unmount();
64 | expect(global.console.error).not.toHaveBeenCalled();
65 | global.console.error = originalErrofn;
66 | });
67 |
68 | it('should render and redirect on 404', async () => {
69 | getIceCream.mockRejectedValueOnce({ response: { status: 404 } });
70 |
71 | const mockLocation = { search: '?iceCreamId=5' };
72 | const mockHistory = { replace: jest.fn(), push: jest.fn() };
73 | render();
74 | await wait(() => {
75 | expect(mockHistory.replace).toHaveBeenCalledWith('/', { focus: true });
76 | });
77 | });
78 |
79 | it('should not redirect on other errors', async () => {
80 | getIceCream.mockRejectedValueOnce({ response: { status: 409 } });
81 |
82 | const mockLocation = { search: '?iceCreamId=5' };
83 | const mockHistory = { push: jest.fn(), replace: jest.fn() };
84 | render();
85 | await wait(() => {
86 | expect(mockHistory.replace).not.toHaveBeenCalled();
87 | });
88 | });
89 |
90 | it('should save a new ice-cream on submit', async () => {
91 | getIceCream.mockResolvedValueOnce({
92 | id: 3,
93 | name: 'Inverted Stoplight',
94 | });
95 |
96 | const mockLocation = { search: '?iceCreamId=5' };
97 | const mockHistory = { push: jest.fn(), replace: jest.fn() };
98 | const { getByLabelText, getByText } = render(
99 |
100 | );
101 | const descriptionTextarea = await waitForElement(() =>
102 | getByLabelText('Description* :')
103 | );
104 | const quantitySelect = getByLabelText('Quantity :');
105 | const priceInput = getByLabelText('Price* :');
106 |
107 | fireEvent.change(descriptionTextarea, {
108 | target: { value: 'This is one cool ice cream' },
109 | });
110 | fireEvent.change(quantitySelect, { target: { value: '20' } });
111 | fireEvent.change(priceInput, { target: { value: '1.45' } });
112 |
113 | const saveButton = getByText('Save');
114 |
115 | await fireEvent.click(saveButton);
116 |
117 | expect(postMenuItem).toHaveBeenCalledWith({
118 | description: 'This is one cool ice cream',
119 | iceCream: { id: 3 },
120 | inStock: true,
121 | price: 1.45,
122 | quantity: 20,
123 | });
124 | expect(mockHistory.push).toHaveBeenCalledWith('/', { focus: true });
125 | });
126 | });
127 |
--------------------------------------------------------------------------------
/src/ice-cream/__tests__/EditIceCream.spec.js:
--------------------------------------------------------------------------------
1 | jest.mock('../../structure/Main');
2 | jest.mock('../../structure/LoaderMessage');
3 | jest.mock('../IceCreamImage');
4 | jest.mock('../../data/iceCreamData');
5 |
6 | import React from 'react';
7 | import {
8 | render,
9 | waitForElement,
10 | wait,
11 | fireEvent,
12 | cleanup,
13 | } from '@testing-library/react';
14 | import EditIceCream from '../EditIceCream';
15 | import {
16 | getMenuItem,
17 | putMenuItem,
18 | deleteMenuItem,
19 | } from '../../data/iceCreamData';
20 |
21 | describe('EditIceCream', () => {
22 | afterEach(cleanup);
23 |
24 | it('should render and load data', async () => {
25 | getMenuItem.mockResolvedValueOnce({
26 | id: 3,
27 | iceCream: { id: 10, name: 'Snowman Godfather' },
28 | inStock: true,
29 | quantity: 30,
30 | price: 1.5,
31 | description: 'Test description',
32 | });
33 |
34 | const mockMatch = { params: { menuItemId: 3 } };
35 |
36 | const { container, getByTestId, getByAltText } = render(
37 |
38 | );
39 |
40 | const heading = await waitForElement(() =>
41 | container.firstChild.querySelector('h2')
42 | );
43 |
44 | expect(heading).toHaveTextContent('Update this beauty');
45 |
46 | expect(getByTestId('loaderMessage')).toHaveTextContent(
47 | 'Loading ice cream.-Ice cream loaded.'
48 | );
49 |
50 | expect(getByAltText('')).toHaveAttribute('src', 'ice-cream-10.svg');
51 |
52 | expect(container.firstChild.querySelector('dl dd')).toHaveTextContent(
53 | 'Snowman Godfather'
54 | );
55 | });
56 |
57 | it('should safely unmount', async () => {
58 | const originalErrofn = global.console.error;
59 |
60 | getMenuItem.mockResolvedValueOnce({
61 | id: 3,
62 | iceCream: { id: 10, name: 'Snowman Godfather' },
63 | inStock: true,
64 | quantity: 30,
65 | price: 1.5,
66 | description: 'Test description',
67 | });
68 |
69 | const mockMatch = { params: { menuItemId: 3 } };
70 | const { unmount } = render();
71 |
72 | global.console.error = jest.fn();
73 |
74 | await unmount();
75 |
76 | expect(global.console.error).not.toHaveBeenCalled();
77 | global.console.error = originalErrofn;
78 | });
79 |
80 | it('should render and redirect on 404', async () => {
81 | getMenuItem.mockRejectedValueOnce({ response: { status: 404 } });
82 |
83 | const mockMatch = { params: { menuItemId: 3 } };
84 |
85 | const mockHistory = { replace: jest.fn(), push: jest.fn() };
86 | render();
87 | await wait(() => {
88 | expect(mockHistory.replace).toHaveBeenCalledWith('/', { focus: true });
89 | });
90 | });
91 |
92 | it('should not redirect on other errors', async () => {
93 | getMenuItem.mockRejectedValueOnce({ response: { status: 409 } });
94 |
95 | const mockMatch = { params: { menuItemId: 3 } };
96 |
97 | const mockHistory = { push: jest.fn(), replace: jest.fn() };
98 | render();
99 | await wait(() => {
100 | expect(mockHistory.replace).not.toHaveBeenCalled();
101 | });
102 | });
103 |
104 | it('should save edited values on submit', async () => {
105 | getMenuItem.mockResolvedValueOnce({
106 | id: 3,
107 | iceCream: { id: 10, name: 'Snowman Godfather' },
108 | inStock: true,
109 | quantity: 30,
110 | price: 1.5,
111 | description: 'Test description',
112 | });
113 |
114 | const mockMatch = { params: { menuItemId: 3 } };
115 | const mockHistory = { push: jest.fn(), replace: jest.fn() };
116 | const { getByLabelText, getByText } = render(
117 |
118 | );
119 | const descriptionTextarea = await waitForElement(() =>
120 | getByLabelText('Description* :')
121 | );
122 | const quantitySelect = getByLabelText('Quantity :');
123 | const priceInput = getByLabelText('Price* :');
124 |
125 | fireEvent.change(descriptionTextarea, {
126 | target: { value: 'This is one cool ice cream' },
127 | });
128 | fireEvent.change(quantitySelect, { target: { value: '20' } });
129 | fireEvent.change(priceInput, { target: { value: '1.45' } });
130 |
131 | const saveButton = getByText('Save');
132 |
133 | await fireEvent.click(saveButton);
134 |
135 | expect(putMenuItem).toHaveBeenCalledWith({
136 | id: 3,
137 | description: 'This is one cool ice cream',
138 | iceCream: { id: 10 },
139 | inStock: true,
140 | price: 1.45,
141 | quantity: 20,
142 | });
143 | expect(mockHistory.push).toHaveBeenCalledWith('/', { focus: true });
144 | });
145 |
146 | it('should delete a menu item', async () => {
147 | getMenuItem.mockResolvedValueOnce({
148 | id: 3,
149 | iceCream: { id: 10, name: 'Snowman Godfather' },
150 | inStock: true,
151 | quantity: 30,
152 | price: 1.5,
153 | description: 'Test description',
154 | });
155 |
156 | const mockMatch = { params: { menuItemId: 3 } };
157 | const mockHistory = { push: jest.fn(), replace: jest.fn() };
158 | const { getByText } = render(
159 |
160 | );
161 |
162 | const deleteButton = await waitForElement(() => getByText('Delete'));
163 |
164 | await fireEvent.click(deleteButton);
165 |
166 | expect(deleteMenuItem).toHaveBeenCalledWith(3);
167 | expect(mockHistory.replace).toHaveBeenCalledWith('/', { focus: true });
168 | });
169 | });
170 |
--------------------------------------------------------------------------------
/src/ice-cream/__tests__/IceCream.spec.js:
--------------------------------------------------------------------------------
1 | jest.mock('../IceCreamImage');
2 |
3 | import React from 'react';
4 | import { render, fireEvent, cleanup } from '@testing-library/react';
5 | import IceCream from '../IceCream';
6 |
7 | describe('IceCream', () => {
8 | afterEach(cleanup);
9 |
10 | it('should render empty', () => {
11 | const mockIceCream = {
12 | id: 1,
13 | name: 'Chocolate Surprise',
14 | };
15 | const { container, getByLabelText, queryByText, getByAltText } = render(
16 |
17 | );
18 |
19 | expect(getByAltText('')).toHaveAttribute('src', 'ice-cream-1.svg');
20 |
21 | expect(container.querySelector('dl dt')).toHaveTextContent('Name :');
22 | expect(container.querySelector('dl dd')).toHaveTextContent(
23 | 'Chocolate Surprise'
24 | );
25 |
26 | expect(getByLabelText('Description* :').value).toBe('');
27 | expect(getByLabelText('In Stock :').checked).toBe(true);
28 | expect(getByLabelText('Quantity :').value).toBe('0');
29 | expect(getByLabelText('Price* :').value).toBe('0.00');
30 |
31 | expect(queryByText('Save')).toBeInTheDocument();
32 | expect(queryByText('Delete')).not.toBeInTheDocument();
33 | });
34 |
35 | it('should render with incoming data', () => {
36 | const mockIceCream = {
37 | id: 1,
38 | name: 'Chocolate Surprise',
39 | };
40 | const { container, getByLabelText, getByAltText } = render(
41 |
49 | );
50 |
51 | expect(getByAltText('')).toHaveAttribute('src', 'ice-cream-1.svg');
52 |
53 | expect(container.querySelector('dl dt')).toHaveTextContent('Name :');
54 | expect(container.querySelector('dl dd')).toHaveTextContent(
55 | 'Chocolate Surprise'
56 | );
57 |
58 | expect(getByLabelText('Description* :').value).toBe('A short description');
59 | expect(getByLabelText('In Stock :').checked).toBe(true);
60 | expect(getByLabelText('Quantity :').value).toBe('20');
61 | expect(getByLabelText('Price* :').value).toBe('1.20');
62 | });
63 |
64 | it('should validate description', () => {
65 | const mockIceCream = {
66 | id: 1,
67 | name: 'Chocolate Surprise',
68 | };
69 |
70 | const { container, getByLabelText, getByText } = render(
71 |
72 | );
73 |
74 | jest.useFakeTimers();
75 |
76 | fireEvent.click(getByText('Save'));
77 |
78 | const descriptionTextarea = getByLabelText('Description* :');
79 |
80 | jest.runAllTimers();
81 |
82 | expect(document.activeElement).toEqual(descriptionTextarea);
83 |
84 | jest.useRealTimers();
85 |
86 | expect(
87 | container.firstChild.querySelector(
88 | `[id="${descriptionTextarea.getAttribute('aria-describedby')}"]`
89 | )
90 | ).toHaveTextContent('You must enter a description');
91 |
92 | fireEvent.change(descriptionTextarea, {
93 | target: { value: 'A short description' },
94 | });
95 |
96 | expect(descriptionTextarea).not.toHaveAttribute('aria-describedby');
97 | });
98 |
99 | it('should validate quantity', () => {
100 | const mockIceCream = {
101 | id: 1,
102 | name: 'Chocolate Surprise',
103 | };
104 |
105 | const { container, getByLabelText, getByText } = render(
106 |
111 | );
112 |
113 | jest.useFakeTimers();
114 |
115 | fireEvent.click(getByText('Save'));
116 |
117 | jest.runAllTimers();
118 |
119 | const quantitySelect = getByLabelText('Quantity :');
120 |
121 | expect(document.activeElement).toEqual(quantitySelect);
122 |
123 | jest.useRealTimers();
124 |
125 | expect(
126 | container.firstChild.querySelector(
127 | `[id="${quantitySelect.getAttribute('aria-describedby')}"]`
128 | )
129 | ).toHaveTextContent('An in stock item should have a quantity');
130 |
131 | fireEvent.change(quantitySelect, {
132 | target: { value: '20' },
133 | });
134 |
135 | expect(quantitySelect).not.toHaveAttribute('aria-describedby');
136 | });
137 |
138 | it('should validate price', () => {
139 | const mockIceCream = {
140 | id: 1,
141 | name: 'Chocolate Surprise',
142 | };
143 |
144 | const { container, getByLabelText, getByText } = render(
145 |
152 | );
153 |
154 | jest.useFakeTimers();
155 |
156 | fireEvent.click(getByText('Save'));
157 | jest.runAllTimers();
158 |
159 | const priceInput = getByLabelText('Price* :');
160 |
161 | expect(document.activeElement).toEqual(priceInput);
162 |
163 | jest.useRealTimers();
164 |
165 | expect(
166 | container.firstChild.querySelector(
167 | `[id="${priceInput.getAttribute('aria-describedby')}"]`
168 | )
169 | ).toHaveTextContent('You must enter a price');
170 |
171 | fireEvent.change(priceInput, {
172 | target: { value: '1.1' },
173 | });
174 |
175 | expect(
176 | container.firstChild.querySelector(
177 | `[id="${priceInput.getAttribute('aria-describedby')}"]`
178 | )
179 | ).toHaveTextContent('Please enter a valid price');
180 |
181 | fireEvent.change(priceInput, {
182 | target: { value: '1.13' },
183 | });
184 |
185 | expect(priceInput).not.toHaveAttribute('aria-describedby');
186 | });
187 |
188 | it('should assist the user when setting "in stock" and "quantity"', () => {
189 | const mockIceCream = {
190 | id: 1,
191 | name: 'Chocolate Surprise',
192 | };
193 |
194 | const { getByLabelText } = render(
195 |
201 | );
202 |
203 | const inStockCheckBox = getByLabelText('In Stock :');
204 | const quantitySelect = getByLabelText('Quantity :');
205 |
206 | fireEvent.click(inStockCheckBox);
207 |
208 | expect(inStockCheckBox.checked).toBe(false);
209 | expect(quantitySelect.value).toBe('0');
210 |
211 | fireEvent.change(quantitySelect, { target: { value: '20' } });
212 |
213 | expect(inStockCheckBox.checked).toBe(true);
214 | expect(quantitySelect.value).toBe('20');
215 | });
216 |
217 | it('should not focus when there is no error', () => {
218 | const mockIceCream = {
219 | id: 1,
220 | name: 'Chocolate Surprise',
221 | };
222 |
223 | const { getByText } = render(
224 |
232 | );
233 |
234 | const saveButton = getByText('Save');
235 | saveButton.focus();
236 |
237 | jest.useFakeTimers();
238 |
239 | fireEvent.click(saveButton);
240 |
241 | jest.runAllTimers();
242 |
243 | jest.useRealTimers();
244 |
245 | expect(document.activeElement).toEqual(saveButton);
246 | });
247 |
248 | it('should submit data', () => {
249 | const mockIceCream = {
250 | id: 1,
251 | name: 'Chocolate Surprise',
252 | };
253 |
254 | const mockSubmitFn = jest.fn();
255 | const { getByText } = render(
256 |
264 | );
265 |
266 | fireEvent.click(getByText('Save'));
267 |
268 | expect(mockSubmitFn).toHaveBeenCalledWith({
269 | description: 'Demo description',
270 | iceCream: { id: 1 },
271 | inStock: true,
272 | price: 1.1,
273 | quantity: 20,
274 | });
275 | });
276 |
277 | it('should fire onDelete if present', () => {
278 | const mockIceCream = {
279 | id: 1,
280 | name: 'Chocolate Surprise',
281 | };
282 |
283 | const mockDeleteFn = jest.fn();
284 | const { getByText } = render(
285 |
294 | );
295 |
296 | fireEvent.click(getByText('Delete'));
297 |
298 | expect(mockDeleteFn).toHaveBeenCalled();
299 | });
300 | });
301 |
--------------------------------------------------------------------------------
/src/ice-cream/__tests__/IceCreamCard.spec.js:
--------------------------------------------------------------------------------
1 | jest.mock('../../structure/FocusLink');
2 | jest.mock('../IceCreamImage');
3 |
4 | import React from 'react';
5 | import { render, cleanup, fireEvent } from '@testing-library/react';
6 | import { IceCreamCard } from '../IceCreamCard';
7 |
8 | describe('IceCreamCard', () => {
9 | afterEach(cleanup);
10 |
11 | it('should render without content', () => {
12 | const { container } = render(
13 |
19 | );
20 | const img = container.firstChild.querySelector('section img');
21 | expect(img).toHaveAttribute('alt', '');
22 | expect(img).toHaveAttribute('src', 'ice-cream-5.svg');
23 |
24 | const anchor = container.firstChild.querySelector('section h3 > a');
25 | expect(anchor).toHaveAttribute('href', '/demo/path');
26 | expect(anchor).toHaveTextContent('Test card heading');
27 | });
28 |
29 | it('should render with content', () => {
30 | const { container } = render(
31 |
37 | I am some text content
38 |
39 | );
40 |
41 | const paragraph = container.firstChild.querySelector('section p');
42 | expect(paragraph).toHaveTextContent('I am some text content');
43 | });
44 |
45 | it('should navigate on container click', () => {
46 | const mockHistory = {
47 | push: jest.fn(),
48 | };
49 |
50 | const { getByText } = render(
51 |
57 | Content
58 |
59 | );
60 |
61 | fireEvent.click(getByText('Content'));
62 | expect(mockHistory.push).toHaveBeenCalledWith('/demo/path');
63 | });
64 |
65 | it('should not double navigate on anchor click', () => {
66 | const mockHistory = {
67 | push: jest.fn(),
68 | };
69 |
70 | const { getByText } = render(
71 |
77 | );
78 |
79 | fireEvent.click(getByText('Test card heading'));
80 | expect(mockHistory.push).not.toHaveBeenCalled();
81 | });
82 | });
83 |
--------------------------------------------------------------------------------
/src/ice-cream/__tests__/IceCreamCardContainer.spec.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { render, cleanup } from '@testing-library/react';
3 | import IceCreamCardContainer from '../IceCreamCardContainer';
4 |
5 | describe('IceCreamCardContainer', () => {
6 | afterEach(cleanup);
7 |
8 | it('should render', () => {
9 | const IceCreamCard = ({ name }) => {name};
10 | const mockData = [
11 | { id: 1, name: 'Todd' },
12 | { id: 2, name: 'Niels' },
13 | { id: 3, name: 'Almero' },
14 | ];
15 |
16 | const { container } = render(
17 |
18 | {mockData.map(item => (
19 |
20 | ))}
21 |
22 | );
23 |
24 | const listItems = container.firstChild.querySelectorAll('ul li');
25 | expect(listItems.length).toBe(3);
26 | expect(listItems[0]).toContainHTML('Todd');
27 | expect(listItems[1]).toContainHTML('Niels');
28 | expect(listItems[2]).toContainHTML('Almero');
29 | });
30 | });
31 |
--------------------------------------------------------------------------------
/src/ice-cream/__tests__/IceCreamImage.spec.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { render, cleanup } from '@testing-library/react';
3 | import IceCreamImage from '../IceCreamImage';
4 |
5 | describe('IceCreamImage', () => {
6 | afterEach(cleanup);
7 | it('should load and display the ice cream image', () => {
8 | const { container } = render();
9 | expect(container.firstChild).toMatchSnapshot();
10 | });
11 | });
12 |
--------------------------------------------------------------------------------
/src/ice-cream/__tests__/IceCreams.spec.js:
--------------------------------------------------------------------------------
1 | jest.mock('../../structure/Main');
2 | jest.mock('../../structure/LoaderMessage');
3 | jest.mock('../IceCreamImage');
4 | jest.mock('../../data/iceCreamData');
5 |
6 | import React from 'react';
7 | import { render, waitForElement, cleanup } from '@testing-library/react';
8 | import IceCreams from '../IceCreams';
9 | import { getIceCreams } from '../../data/iceCreamData';
10 |
11 | const mockData = [
12 | { id: 0, name: 'Stripey Madness' },
13 | { id: 1, name: 'Cherry Blast' },
14 | { id: 2, name: 'Cookie Tower of Power' },
15 | ];
16 |
17 | describe('IceCreams', () => {
18 | afterEach(cleanup);
19 |
20 | it('should render and load data', async () => {
21 | getIceCreams.mockResolvedValueOnce(mockData);
22 |
23 | const { container, getByTestId } = render();
24 |
25 | const heading = await waitForElement(() =>
26 | container.firstChild.querySelector('h2')
27 | );
28 |
29 | expect(heading).toHaveTextContent('Choose your poison and enjoy!');
30 |
31 | expect(getByTestId('loaderMessage')).toHaveTextContent(
32 | 'Loading the stock list.-Loading stock list complete.'
33 | );
34 |
35 | const list = container.firstChild.querySelector('ul');
36 |
37 | const listItems = list.querySelectorAll('li section');
38 | expect(listItems.length).toBe(3);
39 | expect(listItems[0].querySelector('img')).toHaveAttribute(
40 | 'src',
41 | 'ice-cream-0.svg'
42 | );
43 | const firstAnchor = listItems[0].querySelector('h3 a');
44 | expect(firstAnchor).toHaveAttribute('href', '/menu-items/add?iceCreamId=0');
45 | expect(firstAnchor).toHaveTextContent('Stripey Madness');
46 | expect(listItems[1].querySelector('img')).toHaveAttribute(
47 | 'src',
48 | 'ice-cream-1.svg'
49 | );
50 | const secondAnchor = listItems[1].querySelector('h3 a');
51 | expect(secondAnchor).toHaveAttribute(
52 | 'href',
53 | '/menu-items/add?iceCreamId=1'
54 | );
55 | expect(secondAnchor).toHaveTextContent('Cherry Blast');
56 | expect(listItems[2].querySelector('img')).toHaveAttribute(
57 | 'src',
58 | 'ice-cream-2.svg'
59 | );
60 | const thirdAnchor = listItems[2].querySelector('h3 a');
61 | expect(thirdAnchor).toHaveAttribute('href', '/menu-items/add?iceCreamId=2');
62 | expect(thirdAnchor).toHaveTextContent('Cookie Tower of Power');
63 | });
64 |
65 | it('should safely unmount', async () => {
66 | const originalErrofn = global.console.error;
67 |
68 | getIceCreams.mockResolvedValueOnce(mockData);
69 |
70 | const { unmount } = render();
71 | global.console.error = jest.fn();
72 | await unmount();
73 | expect(global.console.error).not.toHaveBeenCalled();
74 | global.console.error = originalErrofn;
75 | });
76 |
77 | it('should render text if the collection is empty', async () => {
78 | getIceCreams.mockResolvedValueOnce([]);
79 |
80 | const { container } = render();
81 |
82 | const placeholder = await waitForElement(() =>
83 | container.firstChild.querySelector('p:not(.visually-hidden)')
84 | );
85 |
86 | expect(placeholder).toHaveTextContent('Your menu is fully stocked!');
87 | });
88 | });
89 |
--------------------------------------------------------------------------------
/src/ice-cream/__tests__/Menu.spec.js:
--------------------------------------------------------------------------------
1 | jest.mock('../../structure/Main');
2 | jest.mock('../../structure/LoaderMessage');
3 | jest.mock('../IceCreamImage');
4 | jest.mock('../../data/iceCreamData');
5 |
6 | import React from 'react';
7 | import { render, waitForElement, cleanup } from '@testing-library/react';
8 | import Menu from '../Menu';
9 | import { getMenu } from '../../data/iceCreamData';
10 |
11 | const mockData = [
12 | {
13 | id: 1,
14 | iceCream: { id: 1, name: 'Cherry Blast' },
15 | inStock: true,
16 | quantity: 20,
17 | price: 1.51,
18 | description:
19 | 'Blast your taste buds into fruity space with this vanilla and cherry bomb',
20 | },
21 | {
22 | id: 2,
23 | iceCream: { id: 15, name: 'Catastrophe' },
24 | inStock: false,
25 | quantity: 0,
26 | price: 1.64,
27 | description: 'A feline strawberry cranium, what could possibly go wrong?',
28 | },
29 | {
30 | id: 3,
31 | iceCream: { id: 10, name: 'Snowman Godfather' },
32 | inStock: true,
33 | quantity: 30,
34 | price: 1.5,
35 | description: "You'll lose your head over this inverted whisky-vanilla cone",
36 | },
37 | ];
38 |
39 | describe('Menu', () => {
40 | afterEach(cleanup);
41 |
42 | it('should render and load data', async () => {
43 | getMenu.mockResolvedValueOnce(mockData);
44 |
45 | const { container, getByTestId } = render();
46 |
47 | const heading = await waitForElement(() =>
48 | container.firstChild.querySelector('h2')
49 | );
50 |
51 | expect(heading).toHaveTextContent(
52 | 'Rock your taste buds with one of these!'
53 | );
54 |
55 | expect(getByTestId('loaderMessage')).toHaveTextContent(
56 | 'Loading menu.-Loading menu complete.'
57 | );
58 |
59 | const list = container.firstChild.querySelector('ul');
60 |
61 | const listItems = list.querySelectorAll('li section');
62 | expect(listItems.length).toBe(3);
63 | expect(listItems[0].querySelector('img')).toHaveAttribute(
64 | 'src',
65 | 'ice-cream-1.svg'
66 | );
67 | expect(listItems[0].querySelector('div.content')).toHaveTextContent(
68 | '$1.5120 in stockBlast your taste buds into fruity space with this vanilla and cherry bomb'
69 | );
70 | const firstAnchor = listItems[0].querySelector('h3 a');
71 | expect(firstAnchor).toHaveAttribute('href', '/menu-items/1');
72 | expect(firstAnchor).toHaveTextContent('Cherry Blast');
73 | expect(listItems[1].querySelector('img')).toHaveAttribute(
74 | 'src',
75 | 'ice-cream-15.svg'
76 | );
77 | expect(listItems[1].querySelector('div.content')).toHaveTextContent(
78 | '$1.64Currently out of stock!A feline strawberry cranium, what could possibly go wrong?'
79 | );
80 | const secondAnchor = listItems[1].querySelector('h3 a');
81 | expect(secondAnchor).toHaveAttribute('href', '/menu-items/2');
82 | expect(secondAnchor).toHaveTextContent('Catastrophe');
83 | expect(listItems[2].querySelector('img')).toHaveAttribute(
84 | 'src',
85 | 'ice-cream-10.svg'
86 | );
87 | expect(listItems[2].querySelector('div.content')).toHaveTextContent(
88 | "$1.5030 in stockYou'll lose your head over this inverted whisky-vanilla cone"
89 | );
90 | const thirdAnchor = listItems[2].querySelector('h3 a');
91 | expect(thirdAnchor).toHaveAttribute('href', '/menu-items/3');
92 | expect(thirdAnchor).toHaveTextContent('Snowman Godfather');
93 | });
94 |
95 | it('should safely unmount', async () => {
96 | const originalErrofn = global.console.error;
97 |
98 | getMenu.mockResolvedValueOnce(mockData);
99 |
100 | const { unmount } = render();
101 | global.console.error = jest.fn();
102 | await unmount();
103 | expect(global.console.error).not.toHaveBeenCalled();
104 | global.console.error = originalErrofn;
105 | });
106 |
107 | it('should render text if the collection is empty', async () => {
108 | getMenu.mockResolvedValueOnce([]);
109 |
110 | const { container } = render();
111 |
112 | const placeholder = await waitForElement(() =>
113 | container.firstChild.querySelector('p:not(.visually-hidden)')
114 | );
115 |
116 | expect(placeholder).toHaveTextContent('Your menu is empty! The sadness!!');
117 | });
118 | });
119 |
--------------------------------------------------------------------------------
/src/ice-cream/__tests__/__snapshots__/IceCreamImage.spec.js.snap:
--------------------------------------------------------------------------------
1 | // Jest Snapshot v1, https://goo.gl/fbAQLP
2 |
3 | exports[`IceCreamImage should load and display the ice cream image 1`] = `
4 |
8 | `;
9 |
--------------------------------------------------------------------------------
/src/index.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import ReactDOM from 'react-dom';
3 | import App from './App';
4 |
5 | ReactDOM.render(, document.getElementById('root'));
6 |
--------------------------------------------------------------------------------
/src/setupTests.js:
--------------------------------------------------------------------------------
1 | import 'jest-dom/extend-expect';
2 |
3 | //This is required to silence a React DOM error that will be fixed in
4 | //version 16.9.0. Once this is released, remove this code.
5 | //Related GitHub issue https://github.com/testing-library/react-testing-library/issues/281#issuecomment-480349256
6 | const originalError = console.error;
7 | beforeAll(() => {
8 | console.error = (...args) => {
9 | if (/Warning.*not wrapped in act/.test(args[0])) {
10 | return;
11 | }
12 | originalError.call(console, ...args);
13 | };
14 | });
15 |
16 | afterAll(() => {
17 | console.error = originalError;
18 | });
19 |
--------------------------------------------------------------------------------
/src/structure/FocusLink.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { Link, NavLink } from 'react-router-dom';
3 | import PropTypes from 'prop-types';
4 |
5 | const FocusLink = ({ to, children, activeClassName, ...props }) => {
6 | const newTo =
7 | typeof to === 'string'
8 | ? {
9 | pathname: to,
10 | state: { focus: true },
11 | }
12 | : {
13 | ...to,
14 | state: to.state ? { ...to.state, focus: true } : { focus: true },
15 | };
16 | return activeClassName ? (
17 |
18 | {children}
19 |
20 | ) : (
21 |
22 | {children}
23 |
24 | );
25 | };
26 |
27 | FocusLink.propTypes = {
28 | to: PropTypes.oneOfType([
29 | PropTypes.string,
30 | PropTypes.shape({
31 | pathname: PropTypes.string.isRequired,
32 | search: PropTypes.string,
33 | state: PropTypes.object,
34 | }),
35 | ]).isRequired,
36 | children: PropTypes.node.isRequired,
37 | activeClassName: PropTypes.string,
38 | };
39 |
40 | export default FocusLink;
41 |
--------------------------------------------------------------------------------
/src/structure/Footer.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { css } from 'emotion/macro';
3 |
4 | const footerStyle = css`
5 | max-width: 63.75em;
6 | margin-left: auto;
7 | margin-right: auto;
8 | border-radius: 0 0 4px 4px;
9 | color: #313030;
10 | text-align: center;
11 | padding-bottom: 2em;
12 |
13 | span {
14 | margin: 0;
15 | font-family: 'cornerstone', sans-serif;
16 | font-weight: 600;
17 | }
18 | `;
19 |
20 | const Footer = () => (
21 |
24 | );
25 |
26 | export default Footer;
27 |
--------------------------------------------------------------------------------
/src/structure/Header.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import FocusLink from '../structure/FocusLink';
3 | import iceCream from '../assets/img/ultimate-ice-cream.svg';
4 | import { css } from 'emotion/macro';
5 |
6 | const headerStyle = css`
7 | position: relative;
8 | text-align: center;
9 | padding-top: 3em;
10 |
11 | h1 {
12 | display: flex;
13 | justify-content: center;
14 | color: #313030;
15 | font-weight: bold;
16 | font-family: 'cornerstone', sans-serif;
17 | font-size: 2.5em;
18 |
19 | img {
20 | margin-right: 0.5em;
21 | }
22 | }
23 |
24 | nav {
25 | max-width: 63.75em;
26 | margin-left: auto;
27 | margin-right: auto;
28 | margin-top: 3em;
29 |
30 | padding: 0.5em;
31 | background-color: #ffffff;
32 | border-radius: 7em;
33 | border: 1px solid rgba(32, 33, 36, 0.12);
34 | background-clip: padding-box;
35 | box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
36 |
37 | display: flex;
38 | align-items: center;
39 |
40 | a {
41 | position: relative;
42 | color: #5c4268;
43 | border: 2px solid transparent;
44 | border-radius: 6em;
45 | padding: 0 0.75em;
46 | font-size: 1em;
47 | line-height: 2em;
48 | text-decoration: none;
49 | transition: box-shadow 0.2s ease-in-out;
50 |
51 | &:hover {
52 | text-decoration: underline;
53 | }
54 |
55 | &:nth-of-type(n + 2) {
56 | &:before {
57 | content: '';
58 | position: absolute;
59 | left: -2px;
60 | top: 15%;
61 | height: 70%;
62 | width: 1px;
63 | background: rgba(32, 33, 36, 0.1);
64 | }
65 | }
66 |
67 | &.active {
68 | color: #a84a7a;
69 | }
70 |
71 | &:focus:not(:active) {
72 | outline: 2px solid transparent;
73 | box-shadow: 0 0 0 2px #8b9099;
74 |
75 | &.active {
76 | box-shadow: 0 0 0 2px #a84a7a;
77 | }
78 | }
79 | }
80 | }
81 | `;
82 |
83 | const Header = () => (
84 |
85 |
86 |
87 | Ultimate Ice Cream
88 |
89 |
97 |
98 | );
99 |
100 | export default Header;
101 |
--------------------------------------------------------------------------------
/src/structure/LoaderMessage.js:
--------------------------------------------------------------------------------
1 | import React, { useState, useLayoutEffect, useRef } from 'react';
2 | import { css } from 'emotion/macro';
3 | import PropTypes from 'prop-types';
4 |
5 | const loaderMessageStyle = css`
6 | .loading {
7 | font-size: 3em;
8 | font-weight: bold;
9 | width: 100%;
10 | text-align: center;
11 | margin: 0;
12 | padding-bottom: 3em;
13 | }
14 | `;
15 |
16 | const LoaderMessage = ({ loadingMsg, doneMsg, isLoading }) => {
17 | const isLoadingPreviousValue = useRef(null);
18 | const loadingMessageDelay = useRef(null);
19 | const doneMessageDelay = useRef(null);
20 | const [showLoadingMessage, setShowLoadingMessage] = useState(false);
21 | const [showDoneMessage, setShowDoneMessage] = useState(false);
22 |
23 | useLayoutEffect(() => {
24 | if (isLoading) {
25 | loadingMessageDelay.current = setTimeout(() => {
26 | setShowLoadingMessage(true);
27 | }, 400);
28 | } else {
29 | if (isLoadingPreviousValue.current) {
30 | setShowDoneMessage(true);
31 | doneMessageDelay.current = setTimeout(() => {
32 | setShowDoneMessage(false);
33 | }, 300);
34 | }
35 | }
36 | isLoadingPreviousValue.current = isLoading;
37 | return () => {
38 | setShowLoadingMessage(false);
39 | setShowDoneMessage(false);
40 | clearTimeout(loadingMessageDelay.current);
41 | clearTimeout(doneMessageDelay.current);
42 | };
43 | }, [isLoading]);
44 |
45 | return (
46 |
51 | {showLoadingMessage &&
{loadingMsg}
}
52 | {showDoneMessage &&
{doneMsg}
}
53 |
54 | );
55 | };
56 |
57 | LoaderMessage.propTypes = {
58 | loadingMsg: PropTypes.string.isRequired,
59 | doneMsg: PropTypes.string.isRequired,
60 | isLoading: PropTypes.bool,
61 | };
62 |
63 | export default LoaderMessage;
64 |
--------------------------------------------------------------------------------
/src/structure/Main.js:
--------------------------------------------------------------------------------
1 | import React, { useRef, useLayoutEffect } from 'react';
2 | import { css } from 'emotion/macro';
3 | import Helmet from 'react-helmet';
4 | import { withRouter } from 'react-router-dom';
5 | import PropTypes from 'prop-types';
6 |
7 | const mainStyle = css`
8 | max-width: 63.75em;
9 | margin-left: auto;
10 | margin-right: auto;
11 | min-height: 40em;
12 | padding-top: 2em;
13 | padding-bottom: 2em;
14 | outline: 0;
15 |
16 | .main-heading {
17 | font-family: 'cornerstone', sans-serif;
18 | padding: 1rem 0 2rem;
19 | color: #313030;
20 | font-size: 1.8em;
21 | outline: 0;
22 | text-align: center;
23 | }
24 | `;
25 |
26 | const Main = ({ headingText, headingLevel = 2, children, location }) => {
27 | const heading = useRef(null);
28 | const H = `h${headingLevel}`;
29 |
30 | useLayoutEffect(() => {
31 | if (location.state && location.state.focus) {
32 | heading.current.focus();
33 | }
34 | window.scrollTo(0, 0);
35 | }, [location.state]);
36 |
37 | return (
38 |
39 |
40 | {headingText} | Ultimate Ice Cream
41 |
42 |
43 | {headingText}
44 |
45 | {children}
46 |
47 | );
48 | };
49 |
50 | Main.propTypes = {
51 | headingText: PropTypes.string.isRequired,
52 | headingLevel: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
53 | children: PropTypes.node.isRequired,
54 | location: PropTypes.shape({
55 | state: PropTypes.shape({
56 | focus: PropTypes.bool,
57 | }),
58 | }).isRequired,
59 | };
60 |
61 | export default withRouter(Main);
62 |
--------------------------------------------------------------------------------
/src/structure/__mocks__/FocusLink.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 |
3 | const FocusLink = ({ to, children, ...props }) => (
4 |
5 | {children}
6 |
7 | );
8 |
9 | export default FocusLink;
10 |
--------------------------------------------------------------------------------
/src/structure/__mocks__/LoaderMessage.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import PropTypes from 'prop-types';
3 |
4 | const LoaderMessage = ({ loadingMsg, doneMsg }) => (
5 |
6 | {loadingMsg}-{doneMsg}
7 |
8 | );
9 |
10 | LoaderMessage.propTypes = {
11 | isLoading: PropTypes.bool.isRequired,
12 | };
13 |
14 | export default LoaderMessage;
15 |
--------------------------------------------------------------------------------
/src/structure/__mocks__/Main.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 |
3 | const Main = ({ headingText, headingLevel = 2, children }) => {
4 | const H = `h${headingLevel}`;
5 | return (
6 |
7 | {headingText}
8 | {children}
9 |
10 | );
11 | };
12 |
13 | export default Main;
14 |
--------------------------------------------------------------------------------
/src/structure/__tests__/FocusLink.spec.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { render, cleanup } from '@testing-library/react';
3 | import FocusLink from '../FocusLink';
4 |
5 | describe('FocusLink', () => {
6 | afterEach(cleanup);
7 |
8 | it('should render as a Link with string to', () => {
9 | const { container } = render(
10 |
11 | Click me
12 |
13 | );
14 |
15 | expect(container.firstChild).toMatchSnapshot();
16 | });
17 |
18 | it('should render as a Link with object to', () => {
19 | const { container } = render(
20 |
24 | Click me
25 |
26 | );
27 |
28 | expect(container.firstChild).toMatchSnapshot();
29 | });
30 |
31 | it('should render as a Link and merge router state', () => {
32 | const { queryByText } = render(
33 |
37 | Click me
38 |
39 | );
40 |
41 | expect(
42 | queryByText('{"someKey":"someVal","focus":true}')
43 | ).toBeInTheDocument();
44 | });
45 |
46 | it('should render as a NavLink with string to', () => {
47 | const { container } = render(
48 |
53 | Click me
54 |
55 | );
56 |
57 | expect(container.firstChild).toMatchSnapshot();
58 | });
59 |
60 | it('should render as a NavLink with object to', () => {
61 | const { container } = render(
62 |
67 | Click me
68 |
69 | );
70 |
71 | expect(container.firstChild).toMatchSnapshot();
72 | });
73 |
74 | it('should render as a NavLink and merge router state', () => {
75 | const { queryByText } = render(
76 |
81 | Click me
82 |
83 | );
84 |
85 | expect(
86 | queryByText('{"someKey":"someVal","focus":true}')
87 | ).toBeInTheDocument();
88 | });
89 | });
90 |
--------------------------------------------------------------------------------
/src/structure/__tests__/Footer.spec.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { render } from '@testing-library/react';
3 | import Footer from '../Footer';
4 |
5 | describe('Footer', () => {
6 | it('should render', () => {
7 | const { container } = render();
8 | expect(container.firstChild).toMatchSnapshot();
9 | });
10 | });
11 |
--------------------------------------------------------------------------------
/src/structure/__tests__/Header.spec.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { render } from '@testing-library/react';
3 | import Header from '../Header';
4 |
5 | describe('Header', () => {
6 | it('should render', () => {
7 | const { container } = render();
8 | const img = container.firstChild.querySelector('header > h1 > img');
9 | expect(img).toHaveAttribute('alt', '');
10 | expect(img).toHaveAttribute('src', 'ultimate-ice-cream.svg');
11 |
12 | const allAnchors = container.firstChild.querySelectorAll('nav a');
13 | expect(allAnchors[0]).toHaveAttribute('href', '/');
14 | expect(allAnchors[0]).toHaveTextContent('Menu');
15 | expect(allAnchors[1]).toHaveAttribute('href', '/ice-creams');
16 | expect(allAnchors[1]).toHaveTextContent('Add Ice Cream');
17 |
18 | const navContainer = container.firstChild.querySelector('nav');
19 | expect(navContainer).toMatchSnapshot();
20 | });
21 | });
22 |
--------------------------------------------------------------------------------
/src/structure/__tests__/LoaderMessage.spec.js:
--------------------------------------------------------------------------------
1 | jest.useFakeTimers();
2 |
3 | import React from 'react';
4 | import { render, cleanup } from '@testing-library/react';
5 | import LoaderMessage from '../LoaderMessage';
6 |
7 | describe('LoaderMessage', () => {
8 | afterEach(cleanup);
9 |
10 | it('should render a loader message', () => {
11 | const { queryByText, rerender } = render(
12 |
17 | );
18 |
19 | expect(queryByText('Busy loading')).not.toBeInTheDocument();
20 | expect(queryByText('Done loading')).not.toBeInTheDocument();
21 |
22 | jest.runTimersToTime(400);
23 |
24 | expect(queryByText('Busy loading')).toBeInTheDocument();
25 | expect(queryByText('Done loading')).not.toBeInTheDocument();
26 |
27 | rerender(
28 |
33 | );
34 |
35 | expect(queryByText('Busy loading')).not.toBeInTheDocument();
36 | expect(queryByText('Done loading')).toBeInTheDocument();
37 |
38 | jest.advanceTimersByTime(300);
39 |
40 | expect(queryByText('Done loading')).not.toBeInTheDocument();
41 | });
42 |
43 | it('should have an assertive live region', () => {
44 | const { container } = render(
45 |
50 | );
51 |
52 | expect(container.firstChild).toHaveAttribute('aria-live', 'assertive');
53 | expect(container.firstChild).toHaveAttribute('aria-atomic', 'true');
54 | });
55 |
56 | it('should not set the done message if toggled from a null prop', () => {
57 | const { queryByText } = render(
58 |
63 | );
64 |
65 | expect(queryByText('Busy loading')).not.toBeInTheDocument();
66 | expect(queryByText('Done loading')).not.toBeInTheDocument();
67 | });
68 | });
69 |
--------------------------------------------------------------------------------
/src/structure/__tests__/Main.spec.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { render, cleanup } from '@testing-library/react';
3 | import Helmet from 'react-helmet';
4 | import Main from '../Main';
5 |
6 | describe('Main', () => {
7 | let oldScrollTo = null;
8 |
9 | beforeEach(() => {
10 | oldScrollTo = global.window.scrollTo;
11 | global.window.scrollTo = jest.fn();
12 | });
13 |
14 | afterEach(() => {
15 | cleanup();
16 | global.window.scrollTo = oldScrollTo;
17 | });
18 |
19 | it('should render with standard heading and set the title', () => {
20 | const { container } = render(
21 |
22 | Page content
23 |
24 | );
25 |
26 | expect(container.firstChild).toMatchSnapshot();
27 | expect(Helmet.peek().title).toEqual([
28 | 'Demo heading',
29 | ' | Ultimate Ice Cream',
30 | ]);
31 | expect(window.scrollTo).toHaveBeenCalledWith(0, 0);
32 | });
33 |
34 | it('should focus the heading if the state dictates', () => {
35 | const { container } = render(
36 |
37 | Page content
38 |
39 | );
40 |
41 | const heading = container.firstChild.querySelector('h2');
42 |
43 | expect(document.activeElement).toEqual(heading);
44 | });
45 |
46 | it('should not focus the heading if the state is absent', () => {
47 | const { container } = render(
48 |
49 | Page content
50 |
51 | );
52 |
53 | const heading = container.firstChild.querySelector('h2');
54 |
55 | expect(document.activeElement).not.toEqual(heading);
56 | });
57 |
58 | it('It should allow for custom heading levels', () => {
59 | const { container } = render(
60 |
61 | Page content
62 |
63 | );
64 |
65 | expect(container.firstChild.querySelector('h3')).toHaveTextContent(
66 | 'Demo heading'
67 | );
68 | });
69 | });
70 |
--------------------------------------------------------------------------------
/src/structure/__tests__/__snapshots__/FocusLink.spec.js.snap:
--------------------------------------------------------------------------------
1 | // Jest Snapshot v1, https://goo.gl/fbAQLP
2 |
3 | exports[`FocusLink should render as a Link with object to 1`] = `
4 |
7 | Click me
8 |
9 | {"focus":true}
10 |
11 |
14 | Link
15 |
16 |
17 | `;
18 |
19 | exports[`FocusLink should render as a Link with string to 1`] = `
20 |
23 | Click me
24 |
25 | {"focus":true}
26 |
27 |
30 | Link
31 |
32 |
33 | `;
34 |
35 | exports[`FocusLink should render as a NavLink with object to 1`] = `
36 |
39 | Click me
40 |
41 | {"focus":true}
42 |
43 |
46 | NavLink
47 |
48 |
49 | `;
50 |
51 | exports[`FocusLink should render as a NavLink with string to 1`] = `
52 |
55 | Click me
56 |
57 | {"focus":true}
58 |
59 |
62 | NavLink
63 |
64 |
65 | `;
66 |
--------------------------------------------------------------------------------
/src/structure/__tests__/__snapshots__/Footer.spec.js.snap:
--------------------------------------------------------------------------------
1 | // Jest Snapshot v1, https://goo.gl/fbAQLP
2 |
3 | exports[`Footer should render 1`] = `
4 | .emotion-0 {
5 | max-width: 63.75em;
6 | margin-left: auto;
7 | margin-right: auto;
8 | border-radius: 0 0 4px 4px;
9 | color: #313030;
10 | text-align: center;
11 | padding-bottom: 2em;
12 | }
13 |
14 | .emotion-0 span {
15 | margin: 0;
16 | font-family: 'cornerstone',sans-serif;
17 | font-weight: 600;
18 | }
19 |
20 |
27 | `;
28 |
--------------------------------------------------------------------------------
/src/structure/__tests__/__snapshots__/Header.spec.js.snap:
--------------------------------------------------------------------------------
1 | // Jest Snapshot v1, https://goo.gl/fbAQLP
2 |
3 | exports[`Header should render 1`] = `
4 |
32 | `;
33 |
--------------------------------------------------------------------------------
/src/structure/__tests__/__snapshots__/Main.spec.js.snap:
--------------------------------------------------------------------------------
1 | // Jest Snapshot v1, https://goo.gl/fbAQLP
2 |
3 | exports[`Main should render with standard heading and set the title 1`] = `
4 | .emotion-0 {
5 | max-width: 63.75em;
6 | margin-left: auto;
7 | margin-right: auto;
8 | min-height: 40em;
9 | padding-top: 2em;
10 | padding-bottom: 2em;
11 | outline: 0;
12 | }
13 |
14 | .emotion-0 .main-heading {
15 | font-family: 'cornerstone',sans-serif;
16 | padding: 1rem 0 2rem;
17 | color: #313030;
18 | font-size: 1.8em;
19 | outline: 0;
20 | text-align: center;
21 | }
22 |
23 |
28 |
32 | Demo heading
33 |
34 |
35 | Page content
36 |
37 |
38 | `;
39 |
--------------------------------------------------------------------------------
/src/utils/__tests__/validators.spec.js:
--------------------------------------------------------------------------------
1 | import {
2 | validateDescription,
3 | validateQuantity,
4 | validatePrice,
5 | } from '../validators';
6 |
7 | describe('Validator validateDescription', () => {
8 | it('should return null for a non-empty description', () => {
9 | expect(validateDescription('a')).toBeNull();
10 | expect(validateDescription('1')).toBeNull();
11 | expect(validateDescription('Some description')).toBeNull();
12 | });
13 |
14 | it('should return a required error message if empty', () => {
15 | expect(validateDescription('')).toBe('You must enter a description');
16 | expect(validateDescription(null)).toBe('You must enter a description');
17 | expect(validateDescription(undefined)).toBe('You must enter a description');
18 | });
19 | });
20 |
21 | describe('Validator validateQuantity', () => {
22 | it('should return null if quantity is zero string for out of stock items', () => {
23 | expect(validateQuantity('0', false)).toBeNull();
24 | });
25 |
26 | it('should return an error message if quantity is zero string for in stock items', () => {
27 | expect(validateQuantity('0', true)).toBe(
28 | 'An in stock item should have a quantity'
29 | );
30 | });
31 | });
32 |
33 | describe('Validator validatePrice', () => {
34 | it('should return null for valid values', () => {
35 | expect(validatePrice('1.12')).toBeNull();
36 | expect(validatePrice('1.10')).toBeNull();
37 | expect(validatePrice('10.98')).toBeNull();
38 | });
39 |
40 | it('should return a required error message if empty', () => {
41 | expect(validatePrice('')).toBe('You must enter a price');
42 | expect(validatePrice(null)).toBe('You must enter a price');
43 | expect(validatePrice(undefined)).toBe('You must enter a price');
44 | });
45 |
46 | it('should return an error message for invalid values', () => {
47 | expect(validatePrice('1')).toBe('Please enter a valid price');
48 | expect(validatePrice('1.')).toBe('Please enter a valid price');
49 | expect(validatePrice('1.1')).toBe('Please enter a valid price');
50 | expect(validatePrice('a')).toBe('Please enter a valid price');
51 | expect(validatePrice('1.G')).toBe('Please enter a valid price');
52 | expect(validatePrice('G.12')).toBe('Please enter a valid price');
53 | });
54 | });
55 |
--------------------------------------------------------------------------------
/src/utils/validators.js:
--------------------------------------------------------------------------------
1 | export const validatePrice = price => {
2 | const regex = /^[0-9]+(\.[0-9][0-9])$/;
3 |
4 | if (!price || price === '0.00') {
5 | return 'You must enter a price';
6 | } else if (!regex.test(price.trim())) {
7 | return 'Please enter a valid price';
8 | }
9 | return null;
10 | };
11 |
12 | export const validateDescription = description =>
13 | description ? null : 'You must enter a description';
14 |
15 | export const validateQuantity = (quantity, inStock) =>
16 | inStock && quantity === '0'
17 | ? 'An in stock item should have a quantity'
18 | : null;
19 |
--------------------------------------------------------------------------------