├── .gitignore
├── README.md
├── cover.png
├── discord.png
├── jest.config.js
├── package.json
├── public
├── favicon.ico
├── index.html
├── logo192.png
├── logo512.png
├── manifest.json
└── robots.txt
├── src
├── App.css
├── App.test.tsx
├── App.tsx
├── CustomInput.test.tsx
├── CustomInput.tsx
├── Pokemon.test.tsx
├── Pokemon.tsx
├── get-user.test.ts
├── get-user.ts
├── index.css
├── index.tsx
├── logo.svg
├── pokemon-example.json
├── react-app-env.d.ts
├── serviceWorker.ts
└── setupTests.ts
├── tsconfig.json
└── yarn.lock
/.gitignore:
--------------------------------------------------------------------------------
1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
2 |
3 | # dependencies
4 | /node_modules
5 | /.pnp
6 | .pnp.js
7 |
8 | # testing
9 | /coverage
10 |
11 | # production
12 | /build
13 |
14 | # misc
15 | .DS_Store
16 | .env.local
17 | .env.development.local
18 | .env.test.local
19 | .env.production.local
20 |
21 | npm-debug.log*
22 | yarn-debug.log*
23 | yarn-error.log*
24 |
25 | # VS Code
26 | .vscode
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Testing React Apps with React Testing Library (RTL)
2 |
3 | Hi! If you are here, that means that you enrolled to my course (or you visited my profile :smirk:).
4 |
5 | You can check out my Udemy course here: [Testing React apps with React Testing Library (RTL) by David Armendáriz](https://www.udemy.com/course/testing-react-apps-with-react-testing-library-rtl/?referralCode=047B3A2FDC682BD91075)
6 |
7 | 
8 |
9 | If you have any questions, you can [join the Discord server](https://discord.gg/ej2F3Qj) of Math as a Second Language
10 |
11 | 
12 |
--------------------------------------------------------------------------------
/cover.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DavidArmendariz/react-testing-course/5016eb48f74343ddddc12d711c9da62fcca902c0/cover.png
--------------------------------------------------------------------------------
/discord.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DavidArmendariz/react-testing-course/5016eb48f74343ddddc12d711c9da62fcca902c0/discord.png
--------------------------------------------------------------------------------
/jest.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | testEnvironment: 'jest-environment-jsdom-sixteen',
3 | };
4 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "react-testing",
3 | "version": "0.1.0",
4 | "private": true,
5 | "dependencies": {
6 | "@types/node": "^14.11.2",
7 | "@types/react": "^16.9.50",
8 | "@types/react-dom": "^16.9.0",
9 | "axios": "^0.20.0",
10 | "react": "^16.13.1",
11 | "react-dom": "^16.13.1",
12 | "react-scripts": "3.4.3"
13 | },
14 | "devDependencies": {
15 | "@testing-library/jest-dom": "^5.11.4",
16 | "@testing-library/react": "^11.0.4",
17 | "@testing-library/user-event": "^12.1.6",
18 | "@types/jest": "^26.0.14",
19 | "jest-environment-jsdom-sixteen": "^1.0.3",
20 | "ts-jest": "^26.4.1",
21 | "typescript": "~4.0.3"
22 | },
23 | "scripts": {
24 | "start": "react-scripts start",
25 | "build": "react-scripts build",
26 | "test": "react-scripts test --env=jest-environment-jsdom-sixteen",
27 | "coverage": "yarn test --coverage --watchAll=false",
28 | "eject": "react-scripts eject"
29 | },
30 | "eslintConfig": {
31 | "extends": "react-app"
32 | },
33 | "browserslist": {
34 | "production": [
35 | ">0.2%",
36 | "not dead",
37 | "not op_mini all"
38 | ],
39 | "development": [
40 | "last 1 chrome version",
41 | "last 1 firefox version",
42 | "last 1 safari version"
43 | ]
44 | },
45 | "jest": {
46 | "collectCoverageFrom": [
47 | "src/**/*.{ts,tsx,js,jsx}",
48 | "!src/serviceWorker.ts",
49 | "!src/index.tsx",
50 | "!src/**/*.d.ts"
51 | ]
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/public/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DavidArmendariz/react-testing-course/5016eb48f74343ddddc12d711c9da62fcca902c0/public/favicon.ico
--------------------------------------------------------------------------------
/public/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
12 |
13 |
17 |
18 |
27 | React App
28 |
29 |
30 |
31 |
32 |
42 |
43 |
44 |
--------------------------------------------------------------------------------
/public/logo192.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DavidArmendariz/react-testing-course/5016eb48f74343ddddc12d711c9da62fcca902c0/public/logo192.png
--------------------------------------------------------------------------------
/public/logo512.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DavidArmendariz/react-testing-course/5016eb48f74343ddddc12d711c9da62fcca902c0/public/logo512.png
--------------------------------------------------------------------------------
/public/manifest.json:
--------------------------------------------------------------------------------
1 | {
2 | "short_name": "React App",
3 | "name": "Create React App Sample",
4 | "icons": [
5 | {
6 | "src": "favicon.ico",
7 | "sizes": "64x64 32x32 24x24 16x16",
8 | "type": "image/x-icon"
9 | },
10 | {
11 | "src": "logo192.png",
12 | "type": "image/png",
13 | "sizes": "192x192"
14 | },
15 | {
16 | "src": "logo512.png",
17 | "type": "image/png",
18 | "sizes": "512x512"
19 | }
20 | ],
21 | "start_url": ".",
22 | "display": "standalone",
23 | "theme_color": "#000000",
24 | "background_color": "#ffffff"
25 | }
26 |
--------------------------------------------------------------------------------
/public/robots.txt:
--------------------------------------------------------------------------------
1 | # https://www.robotstxt.org/robotstxt.html
2 | User-agent: *
3 | Disallow:
4 |
--------------------------------------------------------------------------------
/src/App.css:
--------------------------------------------------------------------------------
1 | .App {
2 | text-align: center;
3 | }
4 |
5 | .App-logo {
6 | height: 40vmin;
7 | pointer-events: none;
8 | }
9 |
10 | @media (prefers-reduced-motion: no-preference) {
11 | .App-logo {
12 | animation: App-logo-spin infinite 20s linear;
13 | }
14 | }
15 |
16 | .App-header {
17 | background-color: #282c34;
18 | min-height: 100vh;
19 | display: flex;
20 | flex-direction: column;
21 | align-items: center;
22 | justify-content: center;
23 | font-size: calc(10px + 2vmin);
24 | color: white;
25 | }
26 |
27 | .App-link {
28 | color: #61dafb;
29 | }
30 |
31 | @keyframes App-logo-spin {
32 | from {
33 | transform: rotate(0deg);
34 | }
35 | to {
36 | transform: rotate(360deg);
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/App.test.tsx:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { render, screen, waitFor } from '@testing-library/react';
3 | import userEvent from '@testing-library/user-event';
4 | import App from './App';
5 | import { getUser } from './get-user';
6 | import { mocked } from 'ts-jest/utils';
7 |
8 | jest.mock('./get-user');
9 | const mockGetUser = mocked(getUser, true);
10 |
11 | describe('When everything is OK', () => {
12 | beforeEach(async () => {
13 | render();
14 | await waitFor(() => expect(mockGetUser).toHaveBeenCalled());
15 | });
16 | test('should render the App component without crashing', () => {
17 | screen.debug();
18 | });
19 |
20 | test('should select the children that is being passed to the CustomInput component', () => {
21 | screen.getAllByText(/Input/);
22 | });
23 |
24 | test('should select the input element by its role', () => {
25 | screen.getAllByRole('textbox');
26 | expect(screen.getAllByRole('textbox')[0]).toBeInTheDocument();
27 | expect(screen.getAllByRole('textbox').length).toEqual(1);
28 | });
29 |
30 | test('should select a label element by its text', () => {
31 | screen.getByLabelText('Input:');
32 | screen.debug();
33 | });
34 |
35 | test('should select input element by placeholder text', () => {
36 | screen.getAllByPlaceholderText('Example');
37 | });
38 |
39 | test('should not find the role "whatever" in our component', () => {
40 | expect(screen.queryByRole('whatever')).toBeNull();
41 | });
42 | });
43 |
44 | describe('When the component fetches the user successfully', () => {
45 | beforeEach(() => {
46 | mockGetUser.mockClear();
47 | });
48 |
49 | test('should call getUser once', async () => {
50 | render();
51 | await waitFor(() => expect(mockGetUser).toHaveBeenCalledTimes(1));
52 | });
53 |
54 | test('should render the username passed', async () => {
55 | const name = 'John';
56 | mockGetUser.mockResolvedValueOnce({ id: '1', name });
57 | render();
58 | expect(screen.queryByText(/Username/)).toBeNull();
59 | expect(await screen.findByText(/Username/)).toBeInTheDocument();
60 | expect(await screen.findByText(`Username: ${name}`)).toBeInTheDocument();
61 | });
62 | });
63 |
64 | describe('When the user enters some text in the input element', () => {
65 | test('should display the text in the screen', async () => {
66 | render();
67 | await waitFor(() => expect(mockGetUser).toHaveBeenCalled());
68 |
69 | expect(screen.getByText(/You typed: .../));
70 |
71 | await userEvent.type(screen.getByRole('textbox'), 'David');
72 |
73 | expect(screen.getByText(/You typed: David/));
74 | });
75 | });
76 |
--------------------------------------------------------------------------------
/src/App.tsx:
--------------------------------------------------------------------------------
1 | import React, { useEffect, useState } from 'react';
2 | import './App.css';
3 | import CustomInput from './CustomInput';
4 | import { getUser, User } from './get-user';
5 |
6 | function App() {
7 | const [text, setText] = useState('');
8 | const [user, setUser] = useState(null);
9 |
10 | useEffect(() => {
11 | const fetchUser = async () => {
12 | const user = await getUser();
13 | setUser(user);
14 | };
15 | fetchUser();
16 | }, []);
17 |
18 | function handleChange(event: React.ChangeEvent) {
19 | setText(event.target.value);
20 | }
21 |
22 | return (
23 |
24 | {user ?
Username: {user.name}
: null}
25 |
26 | Input:
27 |
28 |
You typed: {text ? text : '...'}
29 |
30 | );
31 | }
32 |
33 | export default App;
34 |
--------------------------------------------------------------------------------
/src/CustomInput.test.tsx:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { fireEvent, render, screen } from '@testing-library/react';
3 | import userEvent from '@testing-library/user-event';
4 | import CustomInput from './CustomInput';
5 |
6 | describe('When everything is OK', () => {
7 | test('should call the onChange callback handler when using the fireEvent function', () => {
8 | const onChange = jest.fn();
9 | render(
10 |
11 | Input:
12 |
13 | );
14 | fireEvent.change(screen.getByRole('textbox'), {
15 | target: { value: 'David' },
16 | });
17 | expect(onChange).toHaveBeenCalledTimes(1);
18 | });
19 |
20 | test('should call the onChange callback handler when using the userEvent API', async () => {
21 | const onChange = jest.fn();
22 | render(
23 |
24 | Input:
25 |
26 | );
27 | await userEvent.type(screen.getByRole('textbox'), 'David');
28 | expect(onChange).toHaveBeenCalledTimes(5);
29 | });
30 | });
31 |
--------------------------------------------------------------------------------
/src/CustomInput.tsx:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 |
3 | interface CustomInputProps {
4 | children: React.ReactNode;
5 | value: string;
6 | onChange(event: React.ChangeEvent): void;
7 | }
8 |
9 | function CustomInput({ children, value, onChange }: CustomInputProps) {
10 | return (
11 |
12 |
13 |
20 |
21 | );
22 | }
23 |
24 | export default CustomInput;
25 |
--------------------------------------------------------------------------------
/src/Pokemon.test.tsx:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { render, screen } from '@testing-library/react';
3 | import axios from 'axios';
4 | import Pokemon from './Pokemon';
5 | import userEvent from '@testing-library/user-event';
6 |
7 | jest.mock('axios');
8 | const mockedAxios = axios as jest.Mocked;
9 |
10 | describe('When the user enters a valid pokemon name', () => {
11 | test('should show the pokemon abilities of that pokemon', async () => {
12 | const abilities = [
13 | {
14 | ability: {
15 | name: 'Test ability 1',
16 | url: 'https://ability.com/ability1',
17 | },
18 | },
19 | {
20 | ability: {
21 | name: 'Test ability 2',
22 | url: 'https://ability.com/ability2',
23 | },
24 | },
25 | ];
26 | mockedAxios.get.mockResolvedValueOnce({ data: { abilities } });
27 | render();
28 | await userEvent.type(screen.getByRole('textbox'), 'ditto');
29 | await userEvent.click(screen.getByRole('button'));
30 | const returnedAbilities = await screen.findAllByRole('listitem');
31 | expect(returnedAbilities).toHaveLength(2);
32 | });
33 | });
34 |
35 | describe('When the user enters an invalid pokemon name', () => {
36 | test('should show an error message in the screen', async () => {
37 | mockedAxios.get.mockRejectedValueOnce(new Error());
38 | render();
39 | await userEvent.type(screen.getByRole('textbox'), 'invalid-pokemon-name');
40 | await userEvent.click(screen.getByRole('button'));
41 | const message = await screen.findByText(/Something went wrong/);
42 | expect(message).toBeInTheDocument();
43 | });
44 | });
45 |
--------------------------------------------------------------------------------
/src/Pokemon.tsx:
--------------------------------------------------------------------------------
1 | import React, { useState } from 'react';
2 | import axios from 'axios';
3 | import CustomInput from './CustomInput';
4 |
5 | const pokemonApiUrl = 'https://pokeapi.co/api/v2';
6 |
7 | type Ability = {
8 | ability: {
9 | name: string;
10 | url: string;
11 | };
12 | is_hidden: boolean;
13 | slot: number;
14 | };
15 |
16 | function Pokemon() {
17 | const [pokemonName, setPokemonName] = useState('');
18 | const [pokemonAbilities, setPokemonAbilities] = useState([]);
19 | const [error, setError] = useState(null);
20 |
21 | async function handleFetch(event: React.MouseEvent) {
22 | let result;
23 | try {
24 | result = await axios.get(`${pokemonApiUrl}/pokemon/${pokemonName}`);
25 | setPokemonAbilities(result.data.abilities);
26 | } catch (error) {
27 | setPokemonAbilities([]);
28 | setError(error);
29 | }
30 | }
31 |
32 | function handleChange(event: React.ChangeEvent) {
33 | setPokemonName(event.target.value);
34 | }
35 |
36 | return (
37 |
38 |
39 | Pokemon name:
40 |
41 |
44 | {error &&
Something went wrong...}
45 |
52 |
53 | );
54 | }
55 |
56 | export default Pokemon;
57 |
--------------------------------------------------------------------------------
/src/get-user.test.ts:
--------------------------------------------------------------------------------
1 | import { getUser } from './get-user';
2 |
3 | describe('When everything is OK', () => {
4 | test('should return a response', async () => {
5 | // In a real project, you would use Axios and mock the get method
6 | const result = await getUser();
7 | expect(result).toEqual({ id: '1', name: 'David' });
8 | });
9 | });
10 |
--------------------------------------------------------------------------------
/src/get-user.ts:
--------------------------------------------------------------------------------
1 | export interface User {
2 | id: string;
3 | name: string;
4 | }
5 |
6 | export function getUser(): Promise {
7 | return Promise.resolve({ id: '1', name: 'David' });
8 | }
9 |
--------------------------------------------------------------------------------
/src/index.css:
--------------------------------------------------------------------------------
1 | body {
2 | margin: 0;
3 | font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
4 | 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
5 | sans-serif;
6 | -webkit-font-smoothing: antialiased;
7 | -moz-osx-font-smoothing: grayscale;
8 | }
9 |
10 | code {
11 | font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
12 | monospace;
13 | }
14 |
--------------------------------------------------------------------------------
/src/index.tsx:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import ReactDOM from 'react-dom';
3 | import './index.css';
4 | import * as serviceWorker from './serviceWorker';
5 | import Pokemon from './Pokemon';
6 |
7 | ReactDOM.render(
8 |
9 |
10 | ,
11 | document.getElementById('root')
12 | );
13 |
14 | // If you want your app to work offline and load faster, you can change
15 | // unregister() to register() below. Note this comes with some pitfalls.
16 | // Learn more about service workers: https://bit.ly/CRA-PWA
17 | serviceWorker.unregister();
18 |
--------------------------------------------------------------------------------
/src/logo.svg:
--------------------------------------------------------------------------------
1 |
8 |
--------------------------------------------------------------------------------
/src/react-app-env.d.ts:
--------------------------------------------------------------------------------
1 | ///
2 |
--------------------------------------------------------------------------------
/src/serviceWorker.ts:
--------------------------------------------------------------------------------
1 | // This optional code is used to register a service worker.
2 | // register() is not called by default.
3 |
4 | // This lets the app load faster on subsequent visits in production, and gives
5 | // it offline capabilities. However, it also means that developers (and users)
6 | // will only see deployed updates on subsequent visits to a page, after all the
7 | // existing tabs open on the page have been closed, since previously cached
8 | // resources are updated in the background.
9 |
10 | // To learn more about the benefits of this model and instructions on how to
11 | // opt-in, read https://bit.ly/CRA-PWA
12 |
13 | const isLocalhost = Boolean(
14 | window.location.hostname === 'localhost' ||
15 | // [::1] is the IPv6 localhost address.
16 | window.location.hostname === '[::1]' ||
17 | // 127.0.0.0/8 are considered localhost for IPv4.
18 | window.location.hostname.match(
19 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
20 | )
21 | );
22 |
23 | type Config = {
24 | onSuccess?: (registration: ServiceWorkerRegistration) => void;
25 | onUpdate?: (registration: ServiceWorkerRegistration) => void;
26 | };
27 |
28 | export function register(config?: Config) {
29 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
30 | // The URL constructor is available in all browsers that support SW.
31 | const publicUrl = new URL(
32 | process.env.PUBLIC_URL,
33 | window.location.href
34 | );
35 | if (publicUrl.origin !== window.location.origin) {
36 | // Our service worker won't work if PUBLIC_URL is on a different origin
37 | // from what our page is served on. This might happen if a CDN is used to
38 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374
39 | return;
40 | }
41 |
42 | window.addEventListener('load', () => {
43 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
44 |
45 | if (isLocalhost) {
46 | // This is running on localhost. Let's check if a service worker still exists or not.
47 | checkValidServiceWorker(swUrl, config);
48 |
49 | // Add some additional logging to localhost, pointing developers to the
50 | // service worker/PWA documentation.
51 | navigator.serviceWorker.ready.then(() => {
52 | console.log(
53 | 'This web app is being served cache-first by a service ' +
54 | 'worker. To learn more, visit https://bit.ly/CRA-PWA'
55 | );
56 | });
57 | } else {
58 | // Is not localhost. Just register service worker
59 | registerValidSW(swUrl, config);
60 | }
61 | });
62 | }
63 | }
64 |
65 | function registerValidSW(swUrl: string, config?: Config) {
66 | navigator.serviceWorker
67 | .register(swUrl)
68 | .then(registration => {
69 | registration.onupdatefound = () => {
70 | const installingWorker = registration.installing;
71 | if (installingWorker == null) {
72 | return;
73 | }
74 | installingWorker.onstatechange = () => {
75 | if (installingWorker.state === 'installed') {
76 | if (navigator.serviceWorker.controller) {
77 | // At this point, the updated precached content has been fetched,
78 | // but the previous service worker will still serve the older
79 | // content until all client tabs are closed.
80 | console.log(
81 | 'New content is available and will be used when all ' +
82 | 'tabs for this page are closed. See https://bit.ly/CRA-PWA.'
83 | );
84 |
85 | // Execute callback
86 | if (config && config.onUpdate) {
87 | config.onUpdate(registration);
88 | }
89 | } else {
90 | // At this point, everything has been precached.
91 | // It's the perfect time to display a
92 | // "Content is cached for offline use." message.
93 | console.log('Content is cached for offline use.');
94 |
95 | // Execute callback
96 | if (config && config.onSuccess) {
97 | config.onSuccess(registration);
98 | }
99 | }
100 | }
101 | };
102 | };
103 | })
104 | .catch(error => {
105 | console.error('Error during service worker registration:', error);
106 | });
107 | }
108 |
109 | function checkValidServiceWorker(swUrl: string, config?: Config) {
110 | // Check if the service worker can be found. If it can't reload the page.
111 | fetch(swUrl, {
112 | headers: { 'Service-Worker': 'script' }
113 | })
114 | .then(response => {
115 | // Ensure service worker exists, and that we really are getting a JS file.
116 | const contentType = response.headers.get('content-type');
117 | if (
118 | response.status === 404 ||
119 | (contentType != null && contentType.indexOf('javascript') === -1)
120 | ) {
121 | // No service worker found. Probably a different app. Reload the page.
122 | navigator.serviceWorker.ready.then(registration => {
123 | registration.unregister().then(() => {
124 | window.location.reload();
125 | });
126 | });
127 | } else {
128 | // Service worker found. Proceed as normal.
129 | registerValidSW(swUrl, config);
130 | }
131 | })
132 | .catch(() => {
133 | console.log(
134 | 'No internet connection found. App is running in offline mode.'
135 | );
136 | });
137 | }
138 |
139 | export function unregister() {
140 | if ('serviceWorker' in navigator) {
141 | navigator.serviceWorker.ready
142 | .then(registration => {
143 | registration.unregister();
144 | })
145 | .catch(error => {
146 | console.error(error.message);
147 | });
148 | }
149 | }
150 |
--------------------------------------------------------------------------------
/src/setupTests.ts:
--------------------------------------------------------------------------------
1 | // jest-dom adds custom jest matchers for asserting on DOM nodes.
2 | // allows you to do things like:
3 | // expect(element).toHaveTextContent(/react/i)
4 | // learn more: https://github.com/testing-library/jest-dom
5 | import '@testing-library/jest-dom/extend-expect';
6 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "target": "es5",
4 | "lib": [
5 | "dom",
6 | "dom.iterable",
7 | "esnext"
8 | ],
9 | "allowJs": true,
10 | "skipLibCheck": true,
11 | "esModuleInterop": true,
12 | "allowSyntheticDefaultImports": true,
13 | "strict": true,
14 | "forceConsistentCasingInFileNames": true,
15 | "module": "esnext",
16 | "moduleResolution": "node",
17 | "resolveJsonModule": true,
18 | "isolatedModules": true,
19 | "noEmit": true,
20 | "jsx": "react"
21 | },
22 | "include": [
23 | "src"
24 | ]
25 | }
26 |
--------------------------------------------------------------------------------