Skip to content

Commit 29221f1

Browse files
committed
Initial commit
0 parents  commit 29221f1

23 files changed

+13748
-0
lines changed

.gitignore

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
2+
3+
# dependencies
4+
/node_modules
5+
/.pnp
6+
.pnp.js
7+
8+
# testing
9+
/coverage
10+
11+
# production
12+
/build
13+
14+
# misc
15+
.DS_Store
16+
.env.local
17+
.env.development.local
18+
.env.test.local
19+
.env.production.local
20+
21+
npm-debug.log*
22+
yarn-debug.log*
23+
yarn-error.log*

README.md

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# How to Test React-Query Components
2+
3+
This project has been created to demonstrate how to easily test React components that rely on [React-Query](https://react-query.tanstack.com/) using Jest, Testing Library, Typescript and ChakraUI.
4+
5+
## Medium Article
6+
7+
You can read the Medium article on [How to Test React-Query Components]
8+
//TODO: add URL
9+
10+
## Getting Started
11+
12+
### `yarn start`
13+
14+
Runs the app in the development mode.\
15+
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
16+
17+
The page will reload if you make edits.\
18+
You will also see any lint errors in the console.
19+
20+
### `yarn test`
21+
22+
Launches the test runner in the interactive watch mode.

package.json

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
{
2+
"name": "testing-react-query-components",
3+
"version": "0.1.0",
4+
"private": true,
5+
"dependencies": {
6+
"@chakra-ui/react": "^1.6.2",
7+
"@emotion/react": "11",
8+
"@emotion/styled": "11",
9+
"@testing-library/jest-dom": "^5.11.4",
10+
"@testing-library/react": "^11.1.0",
11+
"@testing-library/user-event": "^12.1.10",
12+
"@types/jest": "^26.0.23",
13+
"@types/node": "^15.3.0",
14+
"@types/react": "^17.0.6",
15+
"@types/react-dom": "^17.0.5",
16+
"framer-motion": "4",
17+
"react": "^17.0.2",
18+
"react-dom": "^17.0.2",
19+
"react-query": "^3.16.0",
20+
"react-scripts": "4.0.3",
21+
"typescript": "^4.1.2",
22+
"web-vitals": "^1.0.1"
23+
},
24+
"scripts": {
25+
"start": "react-scripts start",
26+
"build": "react-scripts build",
27+
"test": "react-scripts test",
28+
"eject": "react-scripts eject"
29+
},
30+
"eslintConfig": {
31+
"extends": [
32+
"react-app",
33+
"react-app/jest"
34+
]
35+
},
36+
"browserslist": {
37+
"production": [
38+
">0.2%",
39+
"not dead",
40+
"not op_mini all"
41+
],
42+
"development": [
43+
"last 1 chrome version",
44+
"last 1 firefox version",
45+
"last 1 safari version"
46+
]
47+
}
48+
}

public/favicon.ico

3.78 KB
Binary file not shown.

public/index.html

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="utf-8" />
5+
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
6+
<meta name="viewport" content="width=device-width, initial-scale=1" />
7+
<meta name="theme-color" content="#000000" />
8+
<meta
9+
name="description"
10+
content="Web site created using create-react-app"
11+
/>
12+
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
13+
<!--
14+
manifest.json provides metadata used when your web app is installed on a
15+
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
16+
-->
17+
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
18+
<!--
19+
Notice the use of %PUBLIC_URL% in the tags above.
20+
It will be replaced with the URL of the `public` folder during the build.
21+
Only files inside the `public` folder can be referenced from the HTML.
22+
23+
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
24+
work correctly both with client-side routing and a non-root public URL.
25+
Learn how to configure a non-root public URL by running `npm run build`.
26+
-->
27+
<title>React App</title>
28+
</head>
29+
<body>
30+
<noscript>You need to enable JavaScript to run this app.</noscript>
31+
<div id="root"></div>
32+
<!--
33+
This HTML file is a template.
34+
If you open it directly in the browser, you will see an empty page.
35+
36+
You can add webfonts, meta tags, or analytics to this file.
37+
The build step will place the bundled scripts into the <body> tag.
38+
39+
To begin the development, run `npm start` or `yarn start`.
40+
To create a production bundle, use `npm run build` or `yarn build`.
41+
-->
42+
</body>
43+
</html>

public/logo192.png

5.22 KB
Loading

public/logo512.png

9.44 KB
Loading

public/manifest.json

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
{
2+
"short_name": "React App",
3+
"name": "Create React App Sample",
4+
"icons": [
5+
{
6+
"src": "favicon.ico",
7+
"sizes": "64x64 32x32 24x24 16x16",
8+
"type": "image/x-icon"
9+
},
10+
{
11+
"src": "logo192.png",
12+
"type": "image/png",
13+
"sizes": "192x192"
14+
},
15+
{
16+
"src": "logo512.png",
17+
"type": "image/png",
18+
"sizes": "512x512"
19+
}
20+
],
21+
"start_url": ".",
22+
"display": "standalone",
23+
"theme_color": "#000000",
24+
"background_color": "#ffffff"
25+
}

public/robots.txt

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# https://www.robotstxt.org/robotstxt.html
2+
User-agent: *
3+
Disallow:

src/App.test.tsx

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import React from "react";
2+
import { render } from "@testing-library/react";
3+
import App from "./App";
4+
import { QueryClient, QueryClientProvider } from "react-query";
5+
6+
test("Renders without crashing", () => {
7+
const client = new QueryClient();
8+
render(
9+
<QueryClientProvider client={client}>
10+
<App />
11+
</QueryClientProvider>,
12+
);
13+
});

src/App.tsx

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import React from 'react';
2+
import { Wrapper } from "./components/Wrapper";
3+
import { StoreApi } from "./services/store";
4+
5+
export const store = new StoreApi("https://fakestoreapi.com");
6+
7+
export default function App() {
8+
return (
9+
<div className="App">
10+
<Wrapper />
11+
</div>
12+
);
13+
}
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
import React from "react";
2+
import { render } from "@testing-library/react";
3+
import { useProduct } from "../hooks/useProduct";
4+
import { ProductDetails } from "./ProductDetails";
5+
6+
// Solves TypeScript Errors
7+
const mockedUseProduct = useProduct as jest.Mock<any>;
8+
9+
// Mock the module
10+
jest.mock("../hooks/useProduct");
11+
12+
describe("<ProductDetails />", () => {
13+
beforeEach(() => {
14+
mockedUseProduct.mockImplementation(() => ({ isLoading: true }));
15+
});
16+
afterEach(() => {
17+
jest.clearAllMocks();
18+
});
19+
20+
it("Renders without crashing", () => {
21+
render(<ProductDetails />);
22+
});
23+
24+
it("Fetches the correct ID", () => {
25+
const { rerender } = render(<ProductDetails />);
26+
27+
// Fetches a default product when `productId` isn't specified (id="1")
28+
expect(useProduct).toHaveBeenCalledWith("1");
29+
30+
rerender(<ProductDetails productId="2" />);
31+
32+
expect(useProduct).toHaveBeenCalledWith("2");
33+
expect(useProduct).toHaveBeenCalledTimes(2);
34+
});
35+
36+
it("Displays loading indicator", () => {
37+
const { getByText } = render(<ProductDetails />);
38+
39+
expect(getByText(/fetching data.../i)).toBeVisible();
40+
});
41+
42+
it("Displays error message", () => {
43+
mockedUseProduct.mockImplementation(() => ({
44+
isLoading: false,
45+
isError: true,
46+
error: { message: "Unable to fetch the product data" },
47+
}));
48+
const { getByText, queryByText } = render(<ProductDetails />);
49+
50+
expect(queryByText(/fetching data/i)).toBeFalsy(); // We don't want the loading flag to be displayed
51+
getByText(/unable to fetch the product data/i);
52+
});
53+
54+
it("Displays data", () => {
55+
const mockedProductData = {
56+
title: "Test Title",
57+
description: "Test Description",
58+
price: 123.45,
59+
category: "Test Category",
60+
image: "https://example.com/image.jpg",
61+
};
62+
mockedUseProduct.mockImplementation(() => ({ isLoading: false, data: mockedProductData }));
63+
64+
const { getByText, queryByText } = render(<ProductDetails />);
65+
66+
// We don't want the loading flag to be displayed
67+
expect(queryByText(/fetching data/i)).toBeFalsy();
68+
69+
getByText(mockedProductData.title);
70+
getByText(mockedProductData.description);
71+
getByText(mockedProductData.category);
72+
getByText(new RegExp(mockedProductData.price.toString()));
73+
});
74+
});

src/components/ProductDetails.tsx

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
import React from "react";
2+
import {
3+
Badge,
4+
Box,
5+
Heading,
6+
Spinner,
7+
Text,
8+
VStack,
9+
Image,
10+
Button,
11+
Alert,
12+
AlertIcon,
13+
AlertTitle,
14+
AlertDescription,
15+
} from "@chakra-ui/react";
16+
import { useProduct } from "../hooks/useProduct";
17+
18+
export interface ProductDetailsProps {
19+
/**
20+
* The ID of the product to be displayed
21+
* @default "1"
22+
*/
23+
productId?: string;
24+
}
25+
export const ProductDetails = ({ productId = "1" }: ProductDetailsProps) => {
26+
const { isLoading, isError, error, data } = useProduct(productId);
27+
if (isLoading) {
28+
return (
29+
<Box>
30+
<Spinner />
31+
<Text>Fetching Data...</Text>
32+
</Box>
33+
);
34+
}
35+
36+
if (isError) {
37+
return (
38+
<Alert status="error">
39+
<AlertIcon />
40+
<AlertTitle mr={2}>Error</AlertTitle>
41+
<AlertDescription>{error?.message}</AlertDescription>
42+
</Alert>
43+
);
44+
}
45+
46+
const { title, price, description, category, image } = data || {};
47+
48+
return (
49+
<Box>
50+
<VStack spacing="3">
51+
<Image src={image} boxSize="150px" data-testid="product-image"/>
52+
<Badge borderRadius="full" px="2" colorScheme="pink">
53+
{category}
54+
</Badge>
55+
<Heading size="lg">{title}</Heading>
56+
<Text>{description}</Text>
57+
<Button colorScheme="blue">Buy Now &bull; ${price}</Button>
58+
</VStack>
59+
</Box>
60+
);
61+
};

src/components/Wrapper.tsx

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import React from "react";
2+
import { Box } from "@chakra-ui/react";
3+
import { ProductDetails } from "./ProductDetails";
4+
5+
export const Wrapper = () => {
6+
// Allow the use of query parameters to define the id of the product to be fetched
7+
const { searchParams } = new URL(window.location.href);
8+
const productId = searchParams.get("id") || "1";
9+
10+
return (
11+
<Box display="flex" alignItems="center" justifyContent="center" height="100vh" background="gray.200">
12+
<Box
13+
maxW="lg"
14+
minW="sm"
15+
borderRadius="lg"
16+
overflow="hidden"
17+
m="10"
18+
p="10"
19+
shadow="xl"
20+
background="white"
21+
textAlign="center"
22+
>
23+
<ProductDetails productId={productId} />
24+
</Box>
25+
</Box>
26+
);
27+
};

src/hooks/useProduct.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
import { useQuery } from "react-query";
2+
import { store } from "../App";
3+
import { Product } from "../services/types";
4+
5+
export const useProduct = (id: string) => {
6+
return useQuery<Product, Error>(["product", id], () => store.getProductById(id), { retry: false })
7+
}

src/index.tsx

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import React, { StrictMode } from "react";
2+
import ReactDOM from "react-dom";
3+
import App from "./App";
4+
import reportWebVitals from "./reportWebVitals";
5+
import { ChakraProvider } from "@chakra-ui/react";
6+
import { QueryClient, QueryClientProvider } from "react-query";
7+
8+
// Initialize React-Query Client
9+
const client = new QueryClient();
10+
11+
const rootElement = document.getElementById("root");
12+
ReactDOM.render(
13+
<StrictMode>
14+
<QueryClientProvider client={client}>
15+
<ChakraProvider>
16+
<App />
17+
</ChakraProvider>
18+
</QueryClientProvider>
19+
</StrictMode>,
20+
rootElement,
21+
);
22+
23+
// If you want to start measuring performance in your app, pass a function
24+
// to log results (for example: reportWebVitals(console.log))
25+
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
26+
reportWebVitals();

0 commit comments

Comments
 (0)