Showing preview only (499K chars total). Download the full file or copy to clipboard to get everything.
Repository: flyrightsister/udemy-react-testing-projects
Branch: main
Commit: b13304c2b1a4
Files: 318
Total size: 421.3 KB
Directory structure:
gitextract_pv9iq0jq/
├── .gitignore
├── COPYING
├── LEGACY-class-based-redux-components/
│ ├── README
│ ├── SOLUTIONS for Jotto Redux Challenges/
│ │ ├── .gitignore
│ │ ├── README.md
│ │ ├── package.json
│ │ ├── public/
│ │ │ ├── index.html
│ │ │ └── manifest.json
│ │ ├── src/
│ │ │ ├── App.css
│ │ │ ├── App.js
│ │ │ ├── App.test.js
│ │ │ ├── Congrats.js
│ │ │ ├── Congrats.test.js
│ │ │ ├── EnterWordButton.js
│ │ │ ├── EnterWordButton.test.js
│ │ │ ├── EnterWordForm.js
│ │ │ ├── EnterWordForm.test.js
│ │ │ ├── GuessedWords.js
│ │ │ ├── GuessedWords.test.js
│ │ │ ├── Input.js
│ │ │ ├── Input.test.js
│ │ │ ├── NewWordButton.js
│ │ │ ├── NewWordButton.test.js
│ │ │ ├── SecretWordReveal.js
│ │ │ ├── SecretWordReveal.test.js
│ │ │ ├── ServerError.js
│ │ │ ├── ServerError.test.js
│ │ │ ├── TotalGuesses.js
│ │ │ ├── TotalGuesses.test.js
│ │ │ ├── actions/
│ │ │ │ ├── index.js
│ │ │ │ └── index.test.js
│ │ │ ├── configureStore.js
│ │ │ ├── helpers/
│ │ │ │ ├── index.js
│ │ │ │ └── index.test.js
│ │ │ ├── index.css
│ │ │ ├── index.js
│ │ │ ├── integration.test.js
│ │ │ ├── reducers/
│ │ │ │ ├── gaveUpReducer.js
│ │ │ │ ├── gaveUpReducer.test.js
│ │ │ │ ├── guessedWordsReducer.js
│ │ │ │ ├── guessedWordsReducer.test.js
│ │ │ │ ├── index.js
│ │ │ │ ├── secretWordReducer.js
│ │ │ │ ├── serverErrorReducer.js
│ │ │ │ ├── serverErrorReducer.test.js
│ │ │ │ ├── successReducer.js
│ │ │ │ ├── successReducer.test.js
│ │ │ │ ├── userEnterReducer.js
│ │ │ │ └── userEnterReducer.test.js
│ │ │ ├── registerServiceWorker.js
│ │ │ └── setupTests.js
│ │ └── test/
│ │ └── testUtils.js
│ └── jotto-redux-class-based/
│ ├── .gitignore
│ ├── README.md
│ ├── package.json
│ ├── public/
│ │ ├── index.html
│ │ └── manifest.json
│ ├── src/
│ │ ├── App.css
│ │ ├── App.js
│ │ ├── App.test.js
│ │ ├── Congrats.js
│ │ ├── Congrats.test.js
│ │ ├── GuessedWords.js
│ │ ├── GuessedWords.test.js
│ │ ├── Input.js
│ │ ├── Input.test.js
│ │ ├── actions/
│ │ │ ├── index.js
│ │ │ └── index.test.js
│ │ ├── configureStore.js
│ │ ├── helpers/
│ │ │ ├── index.js
│ │ │ └── index.test.js
│ │ ├── index.css
│ │ ├── index.js
│ │ ├── integration.test.js
│ │ ├── reducers/
│ │ │ ├── guessedWordsReducer.js
│ │ │ ├── index.js
│ │ │ ├── secretWordReducer.js
│ │ │ ├── successReducer.js
│ │ │ └── successReducer.test.js
│ │ ├── registerServiceWorker.js
│ │ └── setupTests.js
│ └── test/
│ └── testUtils.js
├── README.md
├── SOLUTIONS for Click Counter Challenges/
│ ├── .gitignore
│ ├── .npmrc
│ ├── README.md
│ ├── package.json
│ ├── public/
│ │ ├── index.html
│ │ ├── manifest.json
│ │ └── robots.txt
│ └── src/
│ ├── App.css
│ ├── App.js
│ ├── App.test.js
│ ├── index.css
│ ├── index.js
│ ├── registerServiceWorker.js
│ ├── serviceWorker.js
│ └── setupTests.js
├── SOLUTIONS for Jotto Context Challenges/
│ ├── .npmrc
│ ├── README.md
│ ├── package.json
│ ├── public/
│ │ ├── index.html
│ │ ├── manifest.json
│ │ └── robots.txt
│ ├── src/
│ │ ├── App.css
│ │ ├── App.js
│ │ ├── App.test.js
│ │ ├── Congrats.js
│ │ ├── Congrats.test.js
│ │ ├── EnterSecretWordButton.js
│ │ ├── EnterSecretWordButton.test.js
│ │ ├── GiveUpButton.js
│ │ ├── GiveUpButton.test.js
│ │ ├── GuessedWords.js
│ │ ├── GuessedWords.test.js
│ │ ├── Input.js
│ │ ├── Input.test.js
│ │ ├── LanguagePicker.js
│ │ ├── LanguagePicker.test.js
│ │ ├── NewWordButton.js
│ │ ├── NewWordButton.test.js
│ │ ├── SecretWordEntry.js
│ │ ├── SecretWordEntry.test.js
│ │ ├── SecretWordReveal.js
│ │ ├── SecretWordReveal.test.js
│ │ ├── ServerError.js
│ │ ├── ServerError.test.js
│ │ ├── actions/
│ │ │ ├── hookActions.js
│ │ │ └── hookActions.test.js
│ │ ├── contexts/
│ │ │ ├── guessedWordsContext.js
│ │ │ ├── guessedWordsContext.test.js
│ │ │ ├── languageContext.js
│ │ │ ├── successContext.js
│ │ │ └── successContext.test.js
│ │ ├── helpers/
│ │ │ ├── index.js
│ │ │ ├── index.test.js
│ │ │ ├── strings.js
│ │ │ └── strings.test.js
│ │ ├── index.css
│ │ ├── index.js
│ │ ├── integration_tests/
│ │ │ ├── enter_secret_word.test.js
│ │ │ ├── giveup.test.js
│ │ │ ├── guesses.test.js
│ │ │ └── resetgame.test.js
│ │ ├── serviceWorker.js
│ │ └── setupTests.js
│ └── test/
│ └── testUtils.js
├── SOLUTIONS for Jotto Redux Hooks Challenges/
│ ├── .gitignore
│ ├── .npmrc
│ ├── README.md
│ ├── package.json
│ ├── public/
│ │ ├── index.html
│ │ ├── manifest.json
│ │ └── robots.txt
│ ├── src/
│ │ ├── App.css
│ │ ├── App.js
│ │ ├── App.test.js
│ │ ├── Congrats.js
│ │ ├── Congrats.test.js
│ │ ├── EnterWordButton.js
│ │ ├── EnterWordButton.test.js
│ │ ├── EnterWordForm.js
│ │ ├── EnterWordForm.test.js
│ │ ├── GuessedWords.js
│ │ ├── GuessedWords.test.js
│ │ ├── Input.js
│ │ ├── Input.test.js
│ │ ├── NewWordButton.js
│ │ ├── NewWordButton.test.js
│ │ ├── SecretWordReveal.js
│ │ ├── SecretWordReveal.test.js
│ │ ├── ServerError.js
│ │ ├── ServerError.test.js
│ │ ├── TotalGuesses.js
│ │ ├── TotalGuesses.test.js
│ │ ├── actions/
│ │ │ ├── __mocks__/
│ │ │ │ └── index.js
│ │ │ ├── index.js
│ │ │ └── index.test.js
│ │ ├── config.js.template
│ │ ├── configureStore.js
│ │ ├── guessWord.test.js
│ │ ├── helpers/
│ │ │ ├── index.js
│ │ │ └── index.test.js
│ │ ├── index.css
│ │ ├── index.js
│ │ ├── integration.test.js
│ │ ├── reducers/
│ │ │ ├── gaveUpReducer.js
│ │ │ ├── gaveUpReducer.test.js
│ │ │ ├── guessedWordsReducer.js
│ │ │ ├── index.js
│ │ │ ├── secretWordReducer.js
│ │ │ ├── serverErrorReducer.js
│ │ │ ├── serverErrorReducer.test.js
│ │ │ ├── successReducer.js
│ │ │ ├── successReducer.test.js
│ │ │ ├── userEnterReducer.js
│ │ │ └── userEnterReducer.test.js
│ │ ├── reportWebVitals.js
│ │ └── setupTests.js
│ └── test/
│ └── testUtils.js
├── click-counter/
│ ├── .gitignore
│ ├── .npmrc
│ ├── README.md
│ ├── package.json
│ ├── public/
│ │ ├── index.html
│ │ └── manifest.json
│ └── src/
│ ├── App.css
│ ├── App.js
│ ├── App.test.js
│ ├── index.css
│ ├── index.js
│ ├── registerServiceWorker.js
│ ├── serviceWorker.js
│ └── setupTests.js
├── context-base/
│ ├── .gitignore
│ ├── .npmrc
│ ├── README.md
│ ├── package.json
│ ├── public/
│ │ ├── index.html
│ │ ├── manifest.json
│ │ └── robots.txt
│ ├── src/
│ │ ├── App.css
│ │ ├── App.js
│ │ ├── App.test.js
│ │ ├── Congrats.js
│ │ ├── Congrats.test.js
│ │ ├── GuessedWords.js
│ │ ├── GuessedWords.test.js
│ │ ├── Input.js
│ │ ├── Input.test.js
│ │ ├── actions/
│ │ │ ├── __mocks__/
│ │ │ │ └── index.js
│ │ │ ├── index.js
│ │ │ └── index.test.js
│ │ ├── guessWord.test.js
│ │ ├── helpers/
│ │ │ ├── index.js
│ │ │ └── index.test.js
│ │ ├── index.css
│ │ ├── index.js
│ │ ├── reportWebVitals.js
│ │ └── setupTests.js
│ └── test/
│ └── testUtils.js
├── jotto-context/
│ ├── .gitignore
│ ├── .npmrc
│ ├── README.md
│ ├── package.json
│ ├── public/
│ │ ├── index.html
│ │ ├── manifest.json
│ │ └── robots.txt
│ ├── src/
│ │ ├── App.css
│ │ ├── App.js
│ │ ├── App.test.js
│ │ ├── Congrats.js
│ │ ├── Congrats.test.js
│ │ ├── GuessedWords.js
│ │ ├── GuessedWords.test.js
│ │ ├── Input.js
│ │ ├── Input.test.js
│ │ ├── LanguagePicker.js
│ │ ├── LanguagePicker.test.js
│ │ ├── actions/
│ │ │ ├── __mocks__/
│ │ │ │ └── index.js
│ │ │ ├── index.js
│ │ │ └── index.test.js
│ │ ├── contexts/
│ │ │ ├── guessedWordsContext.js
│ │ │ ├── guessedWordsContext.test.js
│ │ │ ├── languageContext.js
│ │ │ ├── successContext.js
│ │ │ └── successContext.test.js
│ │ ├── guessWord.test.js
│ │ ├── helpers/
│ │ │ ├── index.js
│ │ │ ├── index.test.js
│ │ │ ├── strings.js
│ │ │ └── strings.test.js
│ │ ├── index.css
│ │ ├── index.js
│ │ ├── reportWebVitals.js
│ │ └── setupTests.js
│ └── test/
│ └── testUtils.js
├── jotto-redux-hooks/
│ ├── .gitignore
│ ├── .npmrc
│ ├── README.md
│ ├── package.json
│ ├── public/
│ │ ├── index.html
│ │ ├── manifest.json
│ │ └── robots.txt
│ ├── src/
│ │ ├── App.css
│ │ ├── App.js
│ │ ├── App.test.js
│ │ ├── Congrats.js
│ │ ├── Congrats.test.js
│ │ ├── GuessedWords.js
│ │ ├── GuessedWords.test.js
│ │ ├── Input.js
│ │ ├── Input.test.js
│ │ ├── actions/
│ │ │ ├── __mocks__/
│ │ │ │ └── index.js
│ │ │ ├── index.js
│ │ │ └── index.test.js
│ │ ├── configureStore.js
│ │ ├── guessWord.test.js
│ │ ├── helpers/
│ │ │ ├── index.js
│ │ │ └── index.test.js
│ │ ├── index.css
│ │ ├── index.js
│ │ ├── integration.test.js
│ │ ├── reducers/
│ │ │ ├── guessedWordsReducer.js
│ │ │ ├── index.js
│ │ │ ├── secretWordReducer.js
│ │ │ ├── successReducer.js
│ │ │ └── successReducer.test.js
│ │ ├── reportWebVitals.js
│ │ └── setupTests.js
│ └── test/
│ └── testUtils.js
└── random-word-server/
├── .gitignore
├── .npmrc
├── README.md
├── five-letter-words.json
├── package.json
├── server.js
└── server.test.js
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
node_modules
.DS_Store
.vscode
================================================
FILE: COPYING
================================================
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<http://www.gnu.org/licenses/>.
================================================
FILE: LEGACY-class-based-redux-components/README
================================================
This is legacy code from when the course used class-based
components for the Redux portion. It is NOT maintained!
================================================
FILE: LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/.gitignore
================================================
# See https://help.github.com/ignore-files/ for more about ignoring files.
# dependencies
/node_modules
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
config.js
npm-debug.log*
yarn-debug.log*
yarn-error.log*
================================================
FILE: LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/README.md
================================================
# Jotto
### A React / Redux app used to demonstrate testing
## Solutions
Solutions can be found in the [SOLUTIONS for Jotto Hooks- Context Challenges](https://github.com/flyrightsister/udemy-react-testing-projects/tree/master/SOLUTIONS%20for%20Jotto%20Hooks-Context%20Challenges) folder.
## Challenges
### 1. Number of Guesses

* _Note_: Try to accomplish this _without_ adding a new piece of state!
* Add “guess number” column to the "guessed words" table
* The first guess should show 1, second guess 2, etc.
* Add a component that displays total guesses as shown in wireframe
### 2. Reset Game

* Create a “New word” button component
* only display after successful guess
* Upon click, reset the game with a new word from the server
* _Note_: This can be done with a connected component (which lends itself to state testing similar to `Input.js`) or with an unconnected component which receives the action creator from the parent `App.js` component (which will require unit testing for action creators and reducers instead, as using a store with an unconnected component is not covered in this course). The solution in the `jotto-challenges` branch covers the second approach.
### 3. “Give up” Button


* Create a “Give up” button
* only display when word has not been guessed correctly
* Upon click:
* Show secret word
* Display "better luck next time" message
* Display “new word” button component
### 4. User inputs secret word


* _Note: This one is quite involved, with a new piece of state, Redux Thunk, and testing that an action creator receives the correct argument. Not for the faint of heart! It is great for using existing tests to see whether new code breaks old functionality._
* Add a button for the user to input the secret word
* This way, the user can play against a friend
* After submission, the game should use the user’s secret word, not a word from the server
* This button should disapppear once the user has nonzero `guessedWords`
* Should disappear whether the word came from the server or user input
### 5. Random Word Server Error

* Display an error if:
* There’s a problem contacting the “random word” server
* The server responds with status 4xx or 5xx
### 6. Use Wordnik to get secret word
* Get a [Wordnik auth token](http://developer.wordnik.com/)
* Use the [words/randomWord](http://developer.wordnik.com/docs.html) endpoint (instead of the random word server that came with this course)
## Credits
This project was bootstrapped with [Create React App](https://github.com/facebookincubator/create-react-app).
================================================
FILE: LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/package.json
================================================
{
"name": "jotto",
"version": "0.1.0",
"private": true,
"dependencies": {
"axios": "^0.18.1",
"prop-types": "^15.6.1",
"react": "^16.3.2",
"react-dom": "^16.3.2",
"react-redux": "^5.0.7",
"react-scripts": "1.1.4",
"redux": "^4.0.0",
"redux-thunk": "^2.2.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
},
"devDependencies": {
"ajv": "^6.4.0",
"check-prop-types": "^1.1.2",
"enzyme": "^3.3.0",
"enzyme-adapter-react-16": "^1.1.1",
"jest": "^22.4.3",
"jest-enzyme": "^6.0.0",
"moxios": "^0.4.0"
}
}
================================================
FILE: LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/public/index.html
================================================
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="theme-color" content="#000000">
<!--
manifest.json provides metadata used when your web app is added to the
homescreen on Android. See https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json">
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>
You need to enable JavaScript to run this app.
</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>
================================================
FILE: LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/public/manifest.json
================================================
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
}
],
"start_url": "./index.html",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}
================================================
FILE: LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/App.css
================================================
.spacer-bottom {
margin-bottom: 20px;
}
================================================
FILE: LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/App.js
================================================
import React, { Component } from 'react';
import { connect } from 'react-redux';
import './App.css';
// Challenge #1: Number of Guesses
import TotalGuesses from './TotalGuesses';
// END: Challenge #1: Number of Guesses
// Challenge #2: Reset Game
import NewWordButton from './NewWordButton';
// END: Challenge #2: Reset Game
// Challenge #2: Reset Game
import SecretWordReveal from './SecretWordReveal';
// END: Challenge #2: Reset Game
// Challenge #4: Enter Secret Word
import EnterWordButton from './EnterWordButton';
import EnterWordForm from './EnterWordForm';
// END: Challenge #4: Enter Secret Word
// Challenge #2: Reset Game
import ServerError from './ServerError';
// END: Challenge #2: Reset Game
import GuessedWords from './GuessedWords';
import Congrats from './Congrats';
import Input from './Input';
// Challenge #2 and #4
import {
getSecretWord,
resetGame,
setUserSecretWord,
setUserEntering }
from './actions';
// END: Challenge #2 and #4
export class UnconnectedApp extends Component {
/**
* @method componentDidMount
* @returns {undefined}
*/
componentDidMount() {
// get the secret word
this.props.getSecretWord();
}
render() {
// Challenge #4: Enter Secret Word
let contents;
// Challenge #5: Server Error
if (this.props.serverError) {
contents = <ServerError />
// END: Challenge #5: Server Error
} else if (this.props.userEnter === 'inProgress') {
contents = (
<EnterWordForm formAction={this.props.setUserSecretWord}/>
);
} else {
contents = (
<div>
<Congrats success={this.props.success} />
{/* Challenge #3: Give Up Button */}
<SecretWordReveal display={this.props.gaveUp} secretWord={this.props.secretWord} />
{/* END: Challenge #3: Give Up Button */}
{/* Challenge #2 and #3 */}
<NewWordButton
display={this.props.success || this.props.gaveUp }
resetAction={this.props.resetGame} />
{/* END: Challenge #2 and #3 */}
<Input />
<GuessedWords guessedWords={this.props.guessedWords} />
{/* Challenge #1: Number of guesses */}
<TotalGuesses guessCount={this.props.guessedWords.length} />
{/* END: Challenge #1: Number of guesses */}
{/* Challenge #4: Enter Secret Word */}
<EnterWordButton
display={this.props.guessedWords.length === 0}
buttonAction={this.props.setUserEntering}
/>
{/* END: Challenge #4: Enter Secret Word */}
</div>
);
}
return (
<div className="container">
<h1>Jotto</h1>
{ contents }
</div>
);
// END: Challenge #4: Enter Secret Word
}
}
// Challenge #4: Enter Secret Word
const mapStateToProps = ({ success, guessedWords, secretWord, gaveUp, userEnter, serverError }) => {
return { success, guessedWords, secretWord, gaveUp, userEnter, serverError };
}
// END: Challenge #4: Enter Secret Word
// Challenge #2 and #4
const actions = {
getSecretWord,
resetGame,
setUserSecretWord,
setUserEntering,
};
export default connect(mapStateToProps, actions)(UnconnectedApp);
// END: Challenge #2 and #4
================================================
FILE: LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/App.test.js
================================================
import React from 'react';
import { shallow } from 'enzyme';
import { storeFactory } from '../test/testUtils';
import App, { UnconnectedApp } from './App';
/**
* @function setup
* @param {object} state - State for this setup.
* @returns {ShallowWrapper}
*/
const setup = (state={}) => {
const store = storeFactory(state);
const wrapper = shallow(<App store={store} />).dive();
return wrapper;
}
// Challenge #3: Refactored to set up the wrapper once in a beforeEach
describe('redux properties', () => {
let wrapper;
const success = false;
const gaveUp = false;
const secretWord = 'party';
const guessedWords = [{ guessedWord: 'train', letterMatchCount: 3 }];
beforeEach(() => {
wrapper = setup({
success,
gaveUp,
secretWord,
guessedWords,
});
})
test('has access to `success` state', () => {
const successProp = wrapper.instance().props.success;
expect(successProp).toBe(success);
});
// Challenge #3: Give Up Button
test('has access to `gaveUp` state', () => {
const gaveUpProp = wrapper.instance().props.gaveUp;
expect(gaveUpProp).toBe(gaveUp);
});
// END: Challenge #3: Give Up Button
test('has access to `secretWord` state', () => {
const secretWordProp = wrapper.instance().props.secretWord;
expect(secretWordProp).toBe(secretWord);
});
test('has access to `guessedWords` state', () => {
const guessedWordsProp = wrapper.instance().props.guessedWords;
expect(guessedWordsProp).toEqual(guessedWords);
});
test('`getSecretWord` action creator is a function on the props', () => {
const getSecretWordProp = wrapper.instance().props.getSecretWord;
expect(getSecretWordProp).toBeInstanceOf(Function);
});
// Challenge #2: Reset Game
test('`resetGame` action creator is a function on the props', () => {
const resetGameProp = wrapper.instance().props.resetGame;
expect(resetGameProp).toBeInstanceOf(Function);
});
// END: Challenge #2: Reset Game
});
// END: Challenge #3: Refactored to set up the wrapper once in a beforeEach
test('`getSecretWord` runs on App mount', () => {
const getSecretWordMock = jest.fn();
const props = {
getSecretWord: getSecretWordMock,
success: false,
// Challenge #3: Give Up Button
gaveUp: false,
// END: Challenge #3: Give Up Button
secretWord: 'party',
guessedWords: [],
}
// set up app component with getSecretWordMock as the getSecretWord prop
const wrapper = shallow(<UnconnectedApp {...props} />);
// run lifecycle method
wrapper.instance().componentDidMount();
// check to see if mock ran
const getSecretWordCallCount = getSecretWordMock.mock.calls.length;
expect(getSecretWordCallCount).toBe(1);
});
// NOTE: the logic of what displays according to state
// should be tested here. That is left as an exercise for
// the student. :-)
================================================
FILE: LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/Congrats.js
================================================
import React from 'react';
import PropTypes from 'prop-types';
/**
* Functional react component for congratulatory message.
* @function
* @param {object} props - React props.
* @returns {JSX.Element} - Rendered component (or null if `success` prop is false).
*/
const Congrats = (props) => {
if (props.success) {
return (
<div data-test="component-congrats" className="alert alert-success">
<span data-test="congrats-message">
Congratulations! You guessed the word!
</span>
</div>
);
} else {
return (
<div data-test="component-congrats" />
);
}
};
Congrats.propTypes = {
success: PropTypes.bool.isRequired,
};
export default Congrats;
================================================
FILE: LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/Congrats.test.js
================================================
import React from 'react';
import { shallow } from 'enzyme';
import { findByTestAttr, checkProps } from '../test/testUtils';
import Congrats from './Congrats';
const defaultProps = { success: false };
/**
* Factory function to create a ShallowWrapper for the Congrats component.
* @function setup
* @param {object} props - Component props specific to this setup.
* @returns {ShallowWrapper}
*/
const setup = (props={}) => {
const setupProps = { ...defaultProps, ...props };
return shallow(<Congrats {...setupProps} />)
}
test('renders without error', () => {
const wrapper = setup();
const component = findByTestAttr(wrapper, 'component-congrats');
expect(component.length).toBe(1);
});
test('renders no text when `success` prop is false', () => {
const wrapper = setup({ success: false });
const component = findByTestAttr(wrapper, 'component-congrats');
expect(component.text()).toBe('');
});
test('renders non-empty congrats message when `success` prop is true', () => {
const wrapper = setup({ success: true });
const message = findByTestAttr(wrapper, 'congrats-message');
expect(message.text().length).not.toBe(0);
});
test('does not throw warning with expected props', () => {
const expectedProps = { success: false };
checkProps(Congrats, expectedProps);
});
================================================
FILE: LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/EnterWordButton.js
================================================
// Challenge #4: Enter Secret Word
import React from 'react';
import PropTypes from 'prop-types';
const EnterWordButton = (props) => {
if (props.display) {
return (
<button
data-test="component-enter-word-button"
className="btn btn-primary spacer-bottom"
onClick={props.buttonAction}>
Enter your own secret word
</button>
);
} else {
return (
<div data-test="component-enter-word-button" />
);
}
};
EnterWordButton.propTypes = {
display: PropTypes.bool.isRequired,
buttonAction: PropTypes.func,
};
export default EnterWordButton;
// END: Challenge #4: Enter Secret Word
================================================
FILE: LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/EnterWordButton.test.js
================================================
// Challenge #4: Enter Secret Word
import React from 'react';
import { shallow } from 'enzyme';
import { findByTestAttr, checkProps } from '../test/testUtils';
import EnterWordButton from './EnterWordButton';
const defaultProps = { display: true };
/**
* Factory function to create a ShallowWrapper for the EnterWordButton component.
* @function setup
* @param {object} props - Component props specific to this setup.
* @returns {ShallowWrapper}
*/
const setup = (props={}) => {
const setupProps = { ...defaultProps, ...props };
return shallow(<EnterWordButton {...setupProps} />)
}
describe('render', () => {
test('renders without error', () => {
const wrapper = setup();
const component = findByTestAttr(wrapper, 'component-enter-word-button');
expect(component.length).toBe(1);
});
test('renders no text when `display` prop is false', () => {
const wrapper = setup({ display: false });
const component = findByTestAttr(wrapper, 'component-enter-word-button');
expect(component.text()).toBe('');
});
test('renders non-empty text when `display` prop is true', () => {
const wrapper = setup({ display: true, buttonAction: () => {} });
const component = findByTestAttr(wrapper, 'component-enter-word-button');
expect(component.text().length).not.toBe(0);
});
test('does not throw warning with expected props', () => {
const expectedProps = { display: false };
checkProps(EnterWordButton, expectedProps);
});
});
test('calls `buttonAction` prop upon button click', () => {
// create a mock function so we can see whether it's called on click
const buttonActionMock = jest.fn();
const wrapper = setup({ display: true, buttonAction: buttonActionMock });
// find the button (which is the top level element of this component)
const resetButton = findByTestAttr(wrapper, 'component-enter-word-button');
resetButton.simulate('click');
// expect the mock to have been called once
expect(buttonActionMock.mock.calls.length).toBe(1);
});
// END: Challenge #4: Enter Secret Word
================================================
FILE: LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/EnterWordForm.js
================================================
// Challenge #4: Enter Secret Word
import React from 'react';
import PropTypes from 'prop-types';
export class EnterWordForm extends React.Component {
constructor(props) {
super(props);
this.inputBox = React.createRef();
this.submitForm = this.submitForm.bind(this);
}
submitForm(evt) {
evt.preventDefault();
// don't submit empty word
if (this.inputBox.current.value.length > 0) {
this.props.formAction(this.inputBox.current.value);
}
}
render() {
return (
<div data-test="component-enter-word-form">
<p data-test="enter-word-instructions">
Enter a secret word for someone else to guess!
</p>
<form className="form-inline">
<input
data-test="enter-word-input"
ref={this.inputBox}
className="mb-2 mx-sm-3"
type="text"
placeholder="enter secret word" />
<button
data-test="submit-button"
onClick={this.submitForm}
className="btn btn-primary mb-2"
type="submit">
Submit
</button>
</form>
</div>
);
}
}
EnterWordForm.propTypes = {
formAction: PropTypes.func,
}
export default EnterWordForm;
// END: Challenge #4: Enter Secret Word
================================================
FILE: LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/EnterWordForm.test.js
================================================
// Challenge #4: Enter Secret Word
import React from 'react';
import { shallow } from 'enzyme';
import { findByTestAttr, checkProps } from '../test/testUtils';
import EnterWordForm from './EnterWordForm';
const defaultProps = { formAction: () => {} };
/**
* Factory function to create a ShallowWrapper for the EnterWordForm component.
* @function setup
* @param {object} props - Component props specific to this setup.
* @returns {ShallowWrapper}
*/
const setup = (props={}) => {
const setupProps = { ...defaultProps, ...props };
return shallow(<EnterWordForm {...setupProps} />)
}
describe('render', () => {
// the condition for this to render is within the App
// component, so we don't need to test conditional rendering here
test('renders without error', () => {
const wrapper = setup();
const component = findByTestAttr(wrapper, 'component-enter-word-form');
expect(component.length).toBe(1);
});
test('renders instructions', () => {
const wrapper = setup();
const instructions = findByTestAttr(wrapper, 'enter-word-instructions');
expect(instructions.length).toBe(1);
});
test('renders submit button', () => {
const wrapper = setup();
const submit = findByTestAttr(wrapper, 'submit-button');
expect(submit.length).toBe(1);
});
test('renders input box', () => {
const wrapper = setup();
const input = findByTestAttr(wrapper, 'enter-word-input');
expect(input.length).toBe(1);
});
test('does not throw warning with expected props', () => {
const expectedProps = { formAction: () => {} };
checkProps(EnterWordForm, expectedProps);
});
});
describe('submit click action', () => {
let setUserSecretWordMock;
let wrapper;
const userSecretWord = 'lunch';
beforeEach(() => {
// create a mock function for `setUserSecretWord`
setUserSecretWordMock = jest.fn();
// set up Input, with setUserSecretWordMock as a prop
wrapper = setup({formAction: setUserSecretWordMock});
// simulate the input
wrapper.instance().inputBox.current = { value: userSecretWord };
// simulate click on submit button
const submit = findByTestAttr(wrapper, 'submit-button');
submit.simulate('click', { preventDefault() {} });
});
test('`setUserSecretWord` was called once', () => {
const setUserSecretWordCallCount = setUserSecretWordMock.mock.calls.length;
expect(setUserSecretWordCallCount).toBe(1);
});
test('`setUserSecretWord` was called with input value as argument', () => {
const userSecretWordArg = setUserSecretWordMock.mock.calls[0][0];
expect(userSecretWordArg).toBe(userSecretWord);
});
});
// END: Challenge #4: Enter Secret Word
================================================
FILE: LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/GuessedWords.js
================================================
import React from 'react';
import PropTypes from 'prop-types';
const GuessedWords = (props) => {
let contents
if (props.guessedWords.length === 0) {
contents = (
<span data-test="guess-instructions">
Try to guess the secret word!
</span>
);
} else {
const guessedWordsRows = props.guessedWords.map((word, index) => (
<tr data-test="guessed-word" key={ index }>
{/* Challenge #1: Number of Guesses */}
<td data-test="guessed-word-index">{ index + 1 }</td>
{/* END: Challenge #1: Number of Guesses */}
<td>{ word.guessedWord }</td>
<td>{ word.letterMatchCount }</td>
</tr>
));
contents = (
<div data-test="guessed-words">
<h3>Guessed Words</h3>
<table className="table table-sm">
<thead className="thead-light">
<tr>
{/* Challenge #1: Number of Guesses */}
<th>#</th>
{/* Challenge #1: Number of Guesses */}
<th>Guess</th>
<th>Matching Letters</th>
</tr>
</thead>
<tbody>
{ guessedWordsRows }
</tbody>
</table>
</div>
);
}
return (
<div data-test="component-guessed-words">
{ contents }
</div>
);
};
GuessedWords.propTypes = {
guessedWords: PropTypes.arrayOf(
PropTypes.shape({
guessedWord: PropTypes.string.isRequired,
letterMatchCount: PropTypes.number.isRequired,
})
).isRequired,
};
export default GuessedWords;
================================================
FILE: LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/GuessedWords.test.js
================================================
import React from 'react';
import { shallow } from 'enzyme';
import { findByTestAttr, checkProps } from '../test/testUtils';
import GuessedWords from './GuessedWords';
const defaultProps = {
guessedWords: [{ guessedWord: 'train', letterMatchCount: 3 }],
};
/**
* Factory function to create a ShallowWrapper for the GuessedWords component.
* @function setup
* @param {object} props - Component props specific to this setup.
* @returns {ShallowWrapper}
*/
const setup = (props={}) => {
const setupProps = { ...defaultProps, ...props };
return shallow(<GuessedWords {...setupProps } />)
};
test('does not throw warning with expected props', () => {
checkProps(GuessedWords, defaultProps);
});
describe('if there are no words guessed', () => {
let wrapper
beforeEach(() => {
wrapper = setup({ guessedWords: [] });
});
test('renders without error', () => {
const component = findByTestAttr(wrapper, 'component-guessed-words');
expect(component.length).toBe(1);
});
test('renders instructions to guess a word', () => {
const instructions = findByTestAttr(wrapper, 'guess-instructions');
expect(instructions.text().length).not.toBe(0);
});
});
describe('if there are words guessed', () => {
let wrapper;
const guessedWords = [
{ guessedWord: 'train', letterMatchCount: 3 },
{ guessedWord: 'agile', letterMatchCount: 1 },
{ guessedWord: 'party', letterMatchCount: 5 },
];
beforeEach(() => {
wrapper = setup({ guessedWords });
});
test ('renders without error', () => {
const component = findByTestAttr(wrapper, 'component-guessed-words');
expect(component.length).toBe(1);
});
test('renders "guessed words" section', () => {
const guessedWordsNode = findByTestAttr(wrapper, 'guessed-words');
expect(guessedWordsNode.length).toBe(1);
});
test('correct number of guessed words', () => {
const guessedWordNodes = findByTestAttr(wrapper, 'guessed-word');
expect(guessedWordNodes.length).toBe(guessedWords.length);
});
// Challenge #1: Number of Guesses
test('includes guess word index for each word', () => {
const guessWordIndexes = findByTestAttr(wrapper, 'guessed-word-index');
const indexTextSet = new Set(guessWordIndexes.map(wrapper => wrapper.text()));
const expectedSet = new Set(guessedWords.map((word, index) => (index + 1).toString()));
expect(indexTextSet).toEqual(expectedSet);
});
// END: Challenge #1: Number of Guesses
});
================================================
FILE: LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/Input.js
================================================
import React, { Component } from 'react';
import { connect } from 'react-redux';
// Challenge #3: Give Up Button
import { guessWord, giveUp } from './actions';
// END: Challenge #3: Give Up Button
export class UnconnectedInput extends Component {
/**
* @method constructor
* @param {object} props - Component props.
* @returns {undefined}
*/
constructor(props) {
super(props);
this.inputBox = React.createRef();
this.submitGuessedWord = this.submitGuessedWord.bind(this);
this.giveUpOnClick = this.giveUpOnClick.bind(this);
}
/**
* Run `guessWord` action on the submitted word (if it's not empty)
* @method submitGuessedWord
* @param {Event} evt - Event that triggered the call.
* @returns {undefined}
*/
submitGuessedWord(evt) {
evt.preventDefault();
const guessedWord = this.inputBox.current.value;
if (guessedWord && guessedWord.length > 0) {
this.props.guessWord(guessedWord);
}
this.inputBox.current.value = '';
}
giveUpOnClick(evt) {
evt.preventDefault();
this.props.giveUp();
}
render() {
const contents = this.props.success || this.props.gaveUp
? null
: (
<form className="form-inline">
<input
data-test="input-box"
ref={this.inputBox}
className="mb-2 mx-sm-3"
id="word-guess"
type="text"
placeholer="enter guess" />
<button
data-test="submit-button"
onClick={this.submitGuessedWord}
className="btn btn-primary mb-2"
type="submit">
Submit
</button>
{/* Challenge #3: Give Up Button */}
<button
data-test="give-up-button"
onClick={this.giveUpOnClick}
className="btn btn-danger mb-2">
Give up
</button>
{/* END: Challenge #3: Give Up Button */}
</form>
);
return (
<div data-test="component-input">
{ contents }
</div>
)
}
};
const mapStateToProps = ({ success, gaveUp }) => {
return { success, gaveUp };
}
// Challenge #3: Give Up Button
export default connect(mapStateToProps, { guessWord, giveUp })(UnconnectedInput);
// END: Challenge #3: Give Up Button
================================================
FILE: LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/Input.test.js
================================================
import React from 'react';
import { shallow } from 'enzyme';
import { findByTestAttr, storeFactory } from '../test/testUtils';
import Input, { UnconnectedInput } from './Input';
/**
* Factory function to create a ShallowWrapper for the Input component.
* @function setup
* @param {object} initialState - Initial state for this setup.
* @returns {ShallowWrapper}
*/
const setup = (initialState={}) => {
const store = storeFactory(initialState);
const wrapper = shallow(<Input store={store} />).dive();
return wrapper;
}
describe('render', () => {
describe('word has not been guessed', () => {
let wrapper;
beforeEach(() => {
const initialState = { success: false };
wrapper = setup(initialState);
})
test('renders component without error', () => {
const component = findByTestAttr(wrapper, 'component-input');
expect(component.length).toBe(1);
});
test('renders input box', () => {
const inputBox = findByTestAttr(wrapper, 'input-box');
expect(inputBox.length).toBe(1);
});
test('renders submit button', () => {
const submitButton = findByTestAttr(wrapper, 'submit-button');
expect(submitButton.length).toBe(1);
});
// Challenge #3: Give Up Button
test('renders "give up" button', () => {
const giveUpButton = findByTestAttr(wrapper, 'give-up-button');
expect(giveUpButton.length).toBe(1);
});
// END: Challenge #3: Give Up Button
});
describe('word has been guessed', () => {
let wrapper;
beforeEach(() => {
const initialState = { success: true };
wrapper = setup(initialState);
});
test('renders component without error', () => {
const component = findByTestAttr(wrapper, 'component-input');
expect(component.length).toBe(1);
});
test('does not render input box', () => {
const inputBox = findByTestAttr(wrapper, 'input-box');
expect(inputBox.length).toBe(0);
});
test('does not render submit button', () => {
const submit = findByTestAttr(wrapper, 'submit-button');
expect(submit.length).toBe(0);
});
});
});
describe('redux props', () => {
test('has success piece of state as prop', () => {
const success = true;
const wrapper = setup({ success });
const successProp = wrapper.instance().props.success;
expect(successProp).toBe(success);
});
test('`guessWord` action creator is a function prop', () => {
const wrapper = setup();
const guessWordProp = wrapper.instance().props.guessWord;
expect(guessWordProp).toBeInstanceOf(Function);
})
});
// Challenge #3: Give Up Button
test('calls `giveUp` prop upon "Give Up" button click', () => {
// create a mock function so we can see whether it's called on click
const giveUpMock = jest.fn();
// set up Input, with giveUpMock as a prop
const wrapper = shallow(<UnconnectedInput giveUp={giveUpMock} />);
// simulate click on giveUp button
const giveUpButton = findByTestAttr(wrapper, 'give-up-button');
giveUpButton.simulate('click', { preventDefault() {} });
// expect the mock to have been called once
expect(giveUpMock.mock.calls.length).toBe(1);
});
// END: Challenge #3: Give Up Button
describe('`guessWord` action creator', () => {
let guessWordMock;
let wrapper;
const guessedWord = 'train';
beforeEach(() => {
// create a mock function for `guessWord`
guessWordMock = jest.fn();
// set up Input, with guessWordMock as a prop
wrapper = shallow(<UnconnectedInput guessWord={guessWordMock} />);
// simulate the input
wrapper.instance().inputBox.current = { value: guessedWord };
// simulate click on submit button
const submit = findByTestAttr(wrapper, 'submit-button');
submit.simulate('click', { preventDefault() {} });
});
test('`guessWord` was called once', () => {
const guessWordCallCount = guessWordMock.mock.calls.length;
expect(guessWordCallCount).toBe(1);
});
test('`guessWord` was called with input value as argument', () => {
const guessedWordArg = guessWordMock.mock.calls[0][0];
expect(guessedWordArg).toBe(guessedWord);
});
test('input box clears on submit', () => {
expect(wrapper.instance().inputBox.current.value).toBe('');
})
});
================================================
FILE: LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/NewWordButton.js
================================================
// Challenge #2: Reset Game
import React from 'react';
import PropTypes from 'prop-types';
/**
* Functional react component for reset button.
* @function
* @param {object} props - React props.
* @returns {JSX.Element} - Rendered component (or null if `success` prop is false).
*/
const NewWordButton = (props) => {
if (props.display) {
return (
<button
data-test="component-new-word-button"
className="btn btn-primary spacer-bottom"
onClick={props.resetAction}>
New word
</button>
);
} else {
return (
<div data-test="component-new-word-button" />
);
}
};
NewWordButton.propTypes = {
display: PropTypes.bool.isRequired,
resetAction: PropTypes.func,
};
export default NewWordButton;
// END: Challenge #2: Reset Game
================================================
FILE: LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/NewWordButton.test.js
================================================
// Challenge #2: Reset Game
import React from 'react';
import { shallow } from 'enzyme';
import { findByTestAttr, checkProps } from '../test/testUtils';
import NewWordButton from './NewWordButton';
const defaultProps = { display: false };
/**
* Factory function to create a ShallowWrapper for the NewWordButton component.
* @function setup
* @param {object} props - Component props specific to this setup.
* @returns {ShallowWrapper}
*/
const setup = (props={}) => {
const setupProps = { ...defaultProps, ...props };
return shallow(<NewWordButton {...setupProps} />);
}
describe('render', () => {
test('renders without error', () => {
const wrapper = setup();
const component = findByTestAttr(wrapper, 'component-new-word-button');
expect(component.length).toBe(1);
});
test('renders no text when `display` prop is false', () => {
const wrapper = setup({ display: false });
const component = findByTestAttr(wrapper, 'component-new-word-button');
expect(component.text()).toBe('');
});
test('renders non-empty text when `display` prop is true', () => {
const wrapper = setup({ display: true, resetAction: () => {} });
const component = findByTestAttr(wrapper, 'component-new-word-button');
expect(component.text().length).not.toBe(0);
});
});
test('does not throw warning with expected props', () => {
const expectedProps = { display: false, resetAction: () => {} };
checkProps(NewWordButton, expectedProps);
});
test('calls `resetAction` prop upon button click', () => {
// create a mock function so we can see whether it's called on click
const resetActionMock = jest.fn();
const wrapper = setup({ display: true, resetAction: resetActionMock });
// find the button (which is the top level element of this component)
const resetButton = findByTestAttr(wrapper, 'component-new-word-button');
resetButton.simulate('click');
// expect the mock to have been called once
expect(resetActionMock.mock.calls.length).toBe(1);
});
// END: Challenge #2: Reset Game
================================================
FILE: LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/SecretWordReveal.js
================================================
// Challenge #3: Give Up Button
import React from 'react';
import PropTypes from 'prop-types';
/**
* Functional react component for "you gave up" message.
* @function
* @param {object} props - React props.
* @returns {JSX.Element} - Rendered component (or null if `display` prop is false).
*/
const SecretWordReveal = (props) => {
if (props.display) {
return (
<div data-test="component-secret-word-reveal" className="alert alert-danger">
<span data-test="reveal-message">
The secret word was "{props.secretWord}"<br />
Better luck next time!
</span>
</div>
);
} else {
return (
<div data-test="component-secret-word-reveal" />
);
}
};
SecretWordReveal.propTypes = {
display: PropTypes.bool.isRequired,
// not "isRequired" because it's *not* required if display is false
secretWord: PropTypes.string,
};
export default SecretWordReveal;
// END: Challenge #3: Give Up Button
================================================
FILE: LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/SecretWordReveal.test.js
================================================
// Challenge #3: Give Up Button
import React from 'react';
import { shallow } from 'enzyme';
import { findByTestAttr, checkProps } from '../test/testUtils';
import SecretWordReveal from './SecretWordReveal';
const secretWord = 'party';
const defaultProps = { display: false, secretWord };
/**
* Factory function to create a ShallowWrapper for the SecretWordReveal component.
* @function setup
* @param {object} props - Component props specific to this setup.
* @returns {ShallowWrapper}
*/
const setup = (props={}) => {
const setupProps = { ...defaultProps, ...props };
return shallow(<SecretWordReveal {...setupProps} />)
}
test('renders without error', () => {
const wrapper = setup();
const component = findByTestAttr(wrapper, 'component-secret-word-reveal');
expect(component.length).toBe(1);
});
test('renders no text when `display` prop is false', () => {
const wrapper = setup({ display: false });
const component = findByTestAttr(wrapper, 'component-secret-word-reveal');
expect(component.text()).toBe('');
});
test('renders message containing secret word when `display` prop is true', () => {
const wrapper = setup({ display: true });
const message = findByTestAttr(wrapper, 'reveal-message');
expect(message.text()).toContain(secretWord);
});
test('does not throw warning with expected props', () => {
const expectedProps = { display: false, secretWord };
checkProps(SecretWordReveal, expectedProps);
});
// END: Challenge #3: Give Up Button
================================================
FILE: LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/ServerError.js
================================================
// Challenge #5: Server Error
import React from 'react';
export default (props) => {
return (
<div data-test="component-server-error" className="alert alert-danger">
There was an error retrieving the secret word. Please try again later.
</div>
)
}
// END: Challenge #5: Server Error
================================================
FILE: LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/ServerError.test.js
================================================
// Challenge #5: Server Error
import React from 'react';
import { shallow } from 'enzyme';
import { findByTestAttr } from '../test/testUtils';
import ServerError from './ServerError';
// no need for setup function here: no props or state
test('renders without error', () => {
const wrapper = shallow(<ServerError />);
const component = findByTestAttr(wrapper, 'component-server-error');
expect(component.length).toBe(1);
});
test('renders non-empty text', () => {
const wrapper = shallow(<ServerError />);
const component = findByTestAttr(wrapper, 'component-server-error');
expect(component.text().length).not.toBe(0);
});
// END: Challenge #5: Server Error
================================================
FILE: LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/TotalGuesses.js
================================================
// Challenge #1: Number of Guesses
import React from 'react';
import PropTypes from 'prop-types';
/**
* Functional react component for count of total guesses.
* @function
* @param {object} props - React props.
* @returns {JSX.Element} - Rendered component.
*/
const TotalGuesses = (props) => {
return (
<h4 data-test="component-total-guesses">
Total Guesses: {props.guessCount}
</h4>
);
};
TotalGuesses.propTypes = {
guessCount: PropTypes.number.isRequired,
};
export default TotalGuesses;
// END: Challenge #1: Number of Guesses
================================================
FILE: LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/TotalGuesses.test.js
================================================
// Challenge #1: Number of Guesses
import React from 'react';
import { shallow } from 'enzyme';
import { findByTestAttr, checkProps } from '../test/testUtils';
import TotalGuesses from './TotalGuesses';
const defaultProps = { guessCount: 0 };
/**
* Factory function to create a ShallowWrapper for the TotalGuesses component.
* @function setup
* @param {object} props - Component props specific to this setup.
* @returns {ShallowWrapper}
*/
const setup = (props={}) => {
const setupProps = { ...defaultProps, ...props };
return shallow(<TotalGuesses {...setupProps} />)
}
test('renders without error', () => {
const wrapper = setup();
const component = findByTestAttr(wrapper, 'component-total-guesses');
expect(component.length).toBe(1);
});
test('renders the number of guesses', () => {
const guessCount = 8;
const wrapper = setup({ guessCount });
const component = findByTestAttr(wrapper, 'component-total-guesses');
expect(component.text()).toContain(guessCount.toString());
});
// END: Challenge #1: Number of Guesses
================================================
FILE: LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/actions/index.js
================================================
import axios from 'axios';
import { getLetterMatchCount } from '../helpers';
import { wordnikKey } from '../config.js';
export const WORDNIK_URL = `https://api.wordnik.com/v4/words.json/randomWord?hasDictionaryDef=true&minCorpusCount=1000&minDictionaryCount=100&maxDictionaryCount=-1&minLength=5&maxLength=5&api_key=${wordnikKey}`;
export const actionTypes = {
CORRECT_GUESS: 'CORRECT_GUESS',
GUESS_WORD: 'GUESS_WORD',
SET_SECRET_WORD: 'SET_SECRET_WORD',
RESET_GAME: 'RESET_GAME',
GIVE_UP: 'GIVE_UP',
USER_ENTERING: 'USER_ENTERING',
USER_ENTERED: 'USER_ENTERED',
SERVER_ERROR: 'SERVER_ERROR',
};
/**
* Returns Redux Thunk function that dispatches GUESS_WORD action
* and (conditionally) CORRECT_GUESS action
* @function guessWord
* @param {string} guessedWord - Guessed word.
* @returns {function} - Redux Thunk function.
*/
export const guessWord = (guessedWord) => {
return function(dispatch, getState) {
const secretWord = getState().secretWord;
const letterMatchCount = getLetterMatchCount(guessedWord, secretWord);
dispatch({
type: actionTypes.GUESS_WORD,
payload: { guessedWord, letterMatchCount }
});
if (guessedWord === secretWord) {
dispatch({ type: actionTypes.CORRECT_GUESS });
}
};
};
// Challenge #2: Reset Game
/**
* Dispatch axios action to get secret word from random word server.
* Separate this out so it can be used in getSecretWord and resetGame.
* @function getSecretWordDispatch
* @param {dispatch} dispatch - Redux Thunk dispatch.
*
*/
const getSecretWordDispatch = (dispatch) => {
return axios.get('http://localhost:3030')
.then(response => {
dispatch({
type: actionTypes.SET_SECRET_WORD,
payload: response.data
});
})
// Challenge #5: Server Error
// note: axios rejects promise if status is 4xx or 5xx
.catch(error => {
dispatch ({ type: actionTypes.SERVER_ERROR });
})
// END: Challenge #5: Server Error
};
// Challenge #6: Wordnik
/**
* Dispatch axios action to get secret word from Wordnik.
* Separate this out so it can be used in getSecretWord and resetGame.
* @function getSecretWordWordnikDispatch
* @param {dispatch} dispatch - Redux Thunk dispatch.
*
*/
const getSecretWordWordnikDispatch = (dispatch) => {
return axios.get(WORDNIK_URL)
.then(response => {
dispatch({
type: actionTypes.SET_SECRET_WORD,
// NOTE: to be true to the rules of jotto here,
// we would reject any word with duplicate letters
// and try again. However, my commitment to Jotto is
// not that strong right now. :p
payload: response.data.word
});
})
.catch(err => {
dispatch({ type: actionTypes.SERVER_ERROR })
});
}
// END: Challenge #6: Wordnik
/**
* Returns Redux Thunk function that dispatches GET_SECRET_WORD action
* after axios promise resolves
* @function getSecretWord
* @returns {function} - Redux Thunk function.
*/
export const getSecretWord = () => {
return getSecretWordWordnikDispatch; // Challenge #6: Wordnik
};
/**
* Action creator to reset game and get a new secret word.
* @function resetGame
* @returns {function} - Redux Thunk function that dispatches RESET_GAME action and calls getSecretWord().
*/
export const resetGame = () => {
return (dispatch) => {
dispatch({ type: actionTypes.RESET_GAME });
return getSecretWordWordnikDispatch(dispatch); // Challenge #6: Wordnik
}
};
// END: Challenge #2: Reset Game
// Challenge #3: Give Up Button
/**
* Simple action creator that returns GIVE_UP action type.
* @function giveUp
* @returns {object} - GIVE_UP action type.
*/
export const giveUp = () => {
return { type: actionTypes.GIVE_UP };
};
// END: Challenge #3: Give Up Button
// Challenge #4: Enter Secret Word
/**
* Action creator to dispatch USER_ENTERED and SET_SECRET_WORD actions.
* @function setUserSecretWord
* @param {string} userSecretWord - Secret word entered by user.
* @returns {function} - Redux Thunk function.
*/
export const setUserSecretWord = (userSecretWord) => {
return (dispatch) => {
dispatch({ type: actionTypes.SET_SECRET_WORD, payload: userSecretWord });
dispatch({ type: actionTypes.USER_ENTERED });
}
};
/**
* Action creator that returns USER_ENTERING action type.
* @function setUserEntering
* @returns {object} - Action with type USER_ENTERING.
*/
export const setUserEntering = () => (
{ type: actionTypes.USER_ENTERING }
);
// END: Challenge #4: Enter Secret Word
================================================
FILE: LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/actions/index.test.js
================================================
import moxios from 'moxios';
import { storeFactory } from '../../test/testUtils';
import { getSecretWord } from './';
describe('getSecretWord action creator', () => {
beforeEach(() => {
moxios.install();
});
afterEach(() => {
moxios.uninstall();
});
test('adds response word to state', () => {
const secretWord = 'party';
const store = storeFactory();
moxios.wait(() => {
const request = moxios.requests.mostRecent();
request.respondWith({
status: 200,
// Challenge #6: Wordnik
// NOTE: this is the only thing in the tests that needs to change
// since the shape of the response is different from wordnik
// Otherwise, the tests simply work!
response: { word: secretWord },
// END: Challenge #6: Wordnik
});
});
return store.dispatch(getSecretWord())
.then(() => {
const newState = store.getState();
expect(newState.secretWord).toBe(secretWord);
})
});
describe('updates serverError state to `true`', () => {
// NOTE: there's currently no way to simulate server nonresponse with moxios
test('when server returns 4xx status', () => {
const store = storeFactory();
moxios.wait(() => {
const request = moxios.requests.mostRecent();
request.respondWith({
status: 404,
});
});
return store.dispatch(getSecretWord())
.then(() => {
const newState = store.getState();
expect(newState.serverError).toBe(true);
})
});
test('when server returns 5xx status', () => {
const store = storeFactory();
moxios.wait(() => {
const request = moxios.requests.mostRecent();
request.respondWith({
status: 500,
});
});
return store.dispatch(getSecretWord())
.then(() => {
const newState = store.getState();
expect(newState.serverError).toBe(true);
});
});
})
});
================================================
FILE: LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/configureStore.js
================================================
import { createStore, applyMiddleware } from 'redux';
import ReduxThunk from 'redux-thunk';
import rootReducer from './reducers';
export const middlewares = [ReduxThunk];
const createStoreWithMiddleware = applyMiddleware(...middlewares)(createStore);
export default createStoreWithMiddleware(rootReducer);
================================================
FILE: LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/helpers/index.js
================================================
/**
* @method getLetterMatchCount
* @param {string} guessedWord - Guessed word.
* @param {string} secretWord - Secret word.
* @returns {number} - Number of letters matched between guessed word and secret word.
*/
export function getLetterMatchCount(guessedWord, secretWord) {
const secretLetterSet = new Set(secretWord.split(''));
const guessedLetterSet = new Set(guessedWord.split(''));
return [...secretLetterSet].filter(letter => guessedLetterSet.has(letter)).length;
};
================================================
FILE: LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/helpers/index.test.js
================================================
import { getLetterMatchCount } from './';
describe('getLetterMatchCount', () => {
const secretWord = 'party';
test('returns correct count when there are no matching letters', () => {
const letterMatchCount = getLetterMatchCount('bones', secretWord);
expect(letterMatchCount).toBe(0);
});
test('returns the correct count where there are 3 matching letters', () => {
const letterMatchCount = getLetterMatchCount('train', secretWord);
expect(letterMatchCount).toBe(3);
});
test('returns correct count when there are duplicate letters in the guess', () => {
const letterMatchCount = getLetterMatchCount('parka', secretWord);
expect(letterMatchCount).toBe(3);
});
});
================================================
FILE: LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/index.css
================================================
body {
margin: 0;
padding: 0;
font-family: sans-serif;
}
================================================
FILE: LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/index.js
================================================
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import store from './configureStore';
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root'));
registerServiceWorker();
================================================
FILE: LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/integration.test.js
================================================
import { storeFactory } from '../test/testUtils';
import { guessWord } from './actions';
import { setUserSecretWord } from './actions';
/* Challenge #3 NOTE:
It's a sign that these tests weren't optimally designed that we had to
`giveUp: false` to every `expectedState`. How would you refactor the tests to
be more robust when adding new pieces of state?
*/
describe('guessWord action dispatcher', () => {
const secretWord = 'party';
const unsuccessfulGuess = 'train';
describe('no guessed words', () => {
let store;
const initialState = { secretWord };
beforeEach(() => {
store = storeFactory(initialState);
});
test('updates state correctly for unsuccessful guess', () => {
store.dispatch(guessWord(unsuccessfulGuess));
const newState = store.getState()
const expectedState = {
...initialState,
success: false,
// Challenge #3, 4 and 5
gaveUp: false,
userEnter: null,
serverError: false,
// END: Challenge #3, 4 and 5
guessedWords: [{
guessedWord: unsuccessfulGuess,
letterMatchCount: 3
}]
};
expect(newState).toEqual(expectedState);
});
test('updates state correctly for successful guess', () => {
store.dispatch(guessWord(secretWord));
const newState = store.getState()
const expectedState = {
secretWord,
success: true,
// Challenge #3, 4 and 5
gaveUp: false,
userEnter: null,
serverError: false,
// END: Challenge #3, 4 and 5
guessedWords: [{
guessedWord: secretWord,
letterMatchCount: 5,
}],
};
expect(newState).toEqual(expectedState);
});
});
describe('some guessed words', () => {
const guessedWords = [ { guessedWord: 'agile', letterMatchCount: 1 } ];
const initialState = { guessedWords, secretWord }
let store;
beforeEach(() => {
store = storeFactory(initialState);
})
test('updates state correctly for unsuccessful guess', () => {
store.dispatch(guessWord(unsuccessfulGuess));
const newState = store.getState();
const expectedState = {
secretWord,
success: false,
// Challenge #3, 4 and 5
gaveUp: false,
userEnter: null,
serverError: false,
// END: Challenge #3, 4 and 5
guessedWords: [...guessedWords, { guessedWord: unsuccessfulGuess, letterMatchCount: 3 }]
};
expect(newState).toEqual(expectedState);
});
test('updates state correctly for successful guess', () => {
store.dispatch(guessWord(secretWord));
const newState = store.getState();
const expectedState = {
secretWord,
success: true,
// Challenge #3, 4 and 5
gaveUp: false,
userEnter: null,
serverError: false,
// END: Challenge #3, 4 and 5
guessedWords: [...guessedWords,
{ guessedWord: secretWord, letterMatchCount: 5 }]
};
expect(newState).toEqual(expectedState);
});
});
});
// Challenge #4: Enter Secret Word
describe('setUserSecretWord action dispatcher', () => {
// this is in the integration test section because it
// involves the setUserSecretWord action creator and two reducers
let store;
let newState;
// this represents the word the user entered
const userSecretWord = 'lunch';
// this represents the word we got from the server
const initialState = { secretWord: 'party' };
// here I will run the action in the beforeEach, and
// check on each relevant piece of state separately
beforeEach(() => {
store = storeFactory(initialState);
store.dispatch(setUserSecretWord(userSecretWord));
newState = store.getState();
});
test('updates `secretWord` state correctly after entered word', () => {
expect(newState.secretWord).toBe(userSecretWord);
});
test('updates `userEnter` state correctly after entered word', () => {
expect(newState.userEnter).toBe('done');
});
});
// END: Challenge #4: Enter Secret Word
================================================
FILE: LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/reducers/gaveUpReducer.js
================================================
// Challenge #3: Give Up Button
/* NOTE: This is not the optimal way to track whether or not the user has given up.
With two boolean pieces of state (success aveUp), we have four possibilities:
success=false aveUp=false (user is playing the game)
success=true aveUp=false (user gave up)
success=false aveUp=true (user guessed correctly)
success=true aveUp=true (will never logically happen)
If I were starting from scratch, I would have one piece of state, called, say, 'status'
with three possibilities: inProgress, victory, gaveUp
To refactor to that new scheme now would make this challenge solution more
confusing than necessary, however, so we'll live with the inefficiency.
*/
import { actionTypes } from '../actions';
/**
* @function gaveUp
* @param {boolean} state - Whether the user has given up.
* @param {object} action - Action to be reduced.
* @returns {boolean} - aveUp state.
*/
export default (state=false, action) => {
switch(action.type) {
case (actionTypes.GIVE_UP):
return true;
case (actionTypes.RESET_GAME):
return false;
default:
return state;
}
}
// END: Challenge #3: Give Up Button
================================================
FILE: LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/reducers/gaveUpReducer.test.js
================================================
// Challenge #3: Give Up Button
import { actionTypes } from '../actions';
import gaveUpReducer from './gaveUpReducer';
test('returns default initial state of `false` when no action is passed', () => {
const newState = gaveUpReducer(undefined, {});
expect(newState).toBe(false);
});
test('returns state of true upon receiving an action of type `GIVE_UP`', () => {
const newState = gaveUpReducer(false, { type: actionTypes.GIVE_UP });
expect(newState).toBe(true);
});
test('returns state of false upon receiving an action of type `RESET_GAME`', () => {
// start with giveUp true, since giveUp is false by default
const newState = gaveUpReducer(true, { type: actionTypes.RESET_GAME });
expect(newState).toBe(false);
});
// END: Challenge #3: Give Up Button
================================================
FILE: LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/reducers/guessedWordsReducer.js
================================================
import { actionTypes } from '../actions';
/**
* @function guessedWordsReducer
* @param {array} state - Array of guessed words.
* @param {object} action - action to be reduced.
* @returns {array} - new guessedWords state.
*/
export default (state=[], action) => {
switch(action.type) {
case actionTypes.GUESS_WORD:
return [...state, action.payload];
// Challenge #2: Reset Game
case (actionTypes.RESET_GAME):
return [];
// END: Challenge #2: Reset Game
default:
return state;
}
}
================================================
FILE: LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/reducers/guessedWordsReducer.test.js
================================================
// Challenge #2: Reset Game
import { actionTypes } from '../actions';
import guessedWordsReducer from './guessedWordsReducer';
// Note: Adding guessed words is tested via integration tests in Input.test.js
test('returns state of `[]` upon receiving an action of type `RESET_GAME`', () => {
// start with non-zero guessed words
const initialState = [{ guessedWord: 'train', letterMatchCount: 3 }];
const newState = guessedWordsReducer(initialState, { type: actionTypes.RESET_GAME });
expect(newState).toEqual([]);
});
// END: Challenge #2: Reset Game
================================================
FILE: LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/reducers/index.js
================================================
import { combineReducers } from 'redux';
import success from './successReducer';
import guessedWords from './guessedWordsReducer';
import secretWord from './secretWordReducer';
import userEnter from './userEnterReducer';
// Challenge #3: Give Up Button
import gaveUp from './gaveUpReducer';
// END: Challenge #3: Give Up Button
// Challenge #5: Server Error
import serverError from './serverErrorReducer';
// END: Challenge #5: Server Error
export default combineReducers({
success,
guessedWords,
secretWord,
// Challenge #3: Give Up Button
gaveUp,
// END: Challenge #3: Give Up Button
// Challenge #4: Enter Secret Word
userEnter,
// END: Challenge #4: Enter Secret Word
// Challenge 5: Server Error
serverError,
// END: Challenge #5: Server Error
});
================================================
FILE: LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/reducers/secretWordReducer.js
================================================
import { actionTypes } from '../actions';
/**
* @function secretWordReducer
* @param {string} state - State before reducer.
* @param {object} action - Action sent to reducer.
* @returns {string} - New state (secret word payload from action).
*/
export default (state=null, action) => {
switch (action.type) {
case actionTypes.SET_SECRET_WORD:
return action.payload;
default:
return state;
}
}
================================================
FILE: LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/reducers/serverErrorReducer.js
================================================
// Challenge #5: Server Error
import { actionTypes } from '../actions';
/**
* @function serverErrorReducer
* @param {string} state - State before reducer.
* @param {object} action - Action sent to reducer.
* @returns {string} - New state (depending on action type).
*/
export default (state=false, action) => {
switch (action.type) {
case actionTypes.SERVER_ERROR:
return true;
default:
return state;
}
}
// END: Challenge #5: Server Error
================================================
FILE: LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/reducers/serverErrorReducer.test.js
================================================
// Challenge #5: Server Error
import { actionTypes } from '../actions';
import serverErrorReducer from './serverErrorReducer';
test('returns default initial state of `false` when no action is passed', () => {
const newState = serverErrorReducer(undefined, {});
expect(newState).toBe(false);
});
test('returns state of `true` upon receiving an action of type `SERVER_ERROR`', () => {
const newState = serverErrorReducer(undefined, { type: actionTypes.SERVER_ERROR });
expect(newState).toBe(true);
});
// END: Challenge #5: Server Error
================================================
FILE: LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/reducers/successReducer.js
================================================
import { actionTypes } from '../actions';
/**
* @function successReducer
* @param {boolean} state - Whether the user has guessed correctly.
* @param {object} action - Action to be reduced.
* @returns {boolean} - New success state.
*/
export default (state=false, action) => {
switch(action.type) {
case (actionTypes.CORRECT_GUESS):
return true;
// Challenge #2: Reset Game
case (actionTypes.RESET_GAME):
return false;
// END: Challenge #2: Reset Game
default:
return state;
}
}
================================================
FILE: LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/reducers/successReducer.test.js
================================================
import { actionTypes } from '../actions';
import successReducer from './successReducer';
test('returns default initial state of `false` when no action is passed', () => {
const newState = successReducer(undefined, {});
expect(newState).toBe(false);
});
test('returns state of true upon receiving an action of type `CORRECT_GUESS`', () => {
const newState = successReducer(undefined, { type: actionTypes.CORRECT_GUESS });
expect(newState).toBe(true);
});
// Challenge #2: Reset Game
test('returns state of false upon receiving an action of type `RESET_GAME`', () => {
// start with success true, since success is false by default
const newState = successReducer(true, { type: actionTypes.RESET_GAME });
expect(newState).toBe(false);
});
// END: Challenge #2: Reset Game
================================================
FILE: LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/reducers/userEnterReducer.js
================================================
// Challenge #4: Enter Secret Word
import { actionTypes } from '../actions';
/**
* @function userEnterReducer
* @param {string} state - State before reducer.
* @param {object} action - Action sent to reducer.
* @returns {string} - New state (depending on action type).
*/
export default (state=null, action) => {
switch (action.type) {
case actionTypes.USER_ENTERING:
return 'inProgress';
case actionTypes.USER_ENTERED:
return 'done';
case actionTypes.RESET_GAME:
return null;
default:
return state;
}
}
// END: Challenge #4: Enter Secret Word
================================================
FILE: LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/reducers/userEnterReducer.test.js
================================================
// Challenge #4: Enter Secret Word
import { actionTypes } from '../actions';
import userEnterReducer from './userEnterReducer';
test('returns default initial state of `null` when no action is passed', () => {
const newState = userEnterReducer(undefined, {});
expect(newState).toBeNull();
});
test('returns state of "inProgress" upon receiving an action of type `USER_ENTERING`', () => {
const newState = userEnterReducer(undefined, { type: actionTypes.USER_ENTERING });
expect(newState).toBe('inProgress');
});
test('returns state of "done" upon receiving an action of type `USER_ENTERED`', () => {
// state is most likely to be 'inProgress' at this point
const newState = userEnterReducer('inProgress', { type: actionTypes.USER_ENTERED });
expect(newState).toBe('done');
});
test('returns state of `null` upon receiving an action of type `RESET_GAME`', () => {
// state is most likely to be 'done' at this point
const newState = userEnterReducer('done', { type: actionTypes.RESET_GAME });
expect(newState).toBeNull();
});
// END: Challenge #4: Enter Secret Word
================================================
FILE: LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/registerServiceWorker.js
================================================
// In production, we register a service worker to serve assets from local cache.
// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on the "N+1" visit to a page, since previously
// cached resources are updated in the background.
// To learn more about the benefits of this model, read https://goo.gl/KwvDNy.
// This link also includes instructions on opting out of this behavior.
const isLocalhost = Boolean(
window.location.hostname === 'localhost' ||
// [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' ||
// 127.0.0.1/8 is considered localhost for IPv4.
window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
)
);
export default function register() {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(process.env.PUBLIC_URL, window.location);
if (publicUrl.origin !== window.location.origin) {
// Our service worker won't work if PUBLIC_URL is on a different origin
// from what our page is served on. This might happen if a CDN is used to
// serve assets; see https://github.com/facebookincubator/create-react-app/issues/2374
return;
}
window.addEventListener('load', () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
if (isLocalhost) {
// This is running on localhost. Lets check if a service worker still exists or not.
checkValidServiceWorker(swUrl);
// Add some additional logging to localhost, pointing developers to the
// service worker/PWA documentation.
navigator.serviceWorker.ready.then(() => {
console.log(
'This web app is being served cache-first by a service ' +
'worker. To learn more, visit https://goo.gl/SC7cgQ'
);
});
} else {
// Is not local host. Just register service worker
registerValidSW(swUrl);
}
});
}
}
function registerValidSW(swUrl) {
navigator.serviceWorker
.register(swUrl)
.then(registration => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point, the old content will have been purged and
// the fresh content will have been added to the cache.
// It's the perfect time to display a "New content is
// available; please refresh." message in your web app.
console.log('New content is available; please refresh.');
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log('Content is cached for offline use.');
}
}
};
};
})
.catch(error => {
console.error('Error during service worker registration:', error);
});
}
function checkValidServiceWorker(swUrl) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl)
.then(response => {
// Ensure service worker exists, and that we really are getting a JS file.
if (
response.status === 404 ||
response.headers.get('content-type').indexOf('javascript') === -1
) {
// No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then(registration => {
registration.unregister().then(() => {
window.location.reload();
});
});
} else {
// Service worker found. Proceed as normal.
registerValidSW(swUrl);
}
})
.catch(() => {
console.log(
'No internet connection found. App is running in offline mode.'
);
});
}
export function unregister() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready.then(registration => {
registration.unregister();
});
}
}
================================================
FILE: LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/setupTests.js
================================================
import Enzyme, { shallow } from 'enzyme';
import EnzymeAdapter from 'enzyme-adapter-react-16';
Enzyme.configure({
adapter: new EnzymeAdapter(),
disableLifecycleMethods: true,
});
================================================
FILE: LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/test/testUtils.js
================================================
import checkPropTypes from 'check-prop-types';
import { createStore, applyMiddleware } from 'redux';
import rootReducer from '../src/reducers';
import { middlewares } from '../src/configureStore';
/**
* Create a testing store with imported reducers, middleware, and initial state.
* globals: rootReducer, middlewares.
* @param {object} initialState - Initial state for store.
* @function storeFactory
* @returns {Store} - Redux store.
*/
export const storeFactory = (initialState) => {
const createStoreWithMiddleware = applyMiddleware(...middlewares)(createStore)
return createStoreWithMiddleware(rootReducer, initialState);
}
/**
* Return node(s) with the given data-test attribute.
* @param {ShallowWrapper} wrapper - Enzyme shallow wrapper.
* @param {string} val - Value of data-test attribute for search.
* @returns {ShallowWrapper}
*/
export const findByTestAttr = (wrapper, val) => {
return wrapper.find(`[data-test="${val}"]`);
}
export const checkProps = (component, conformingProps) => {
const propError = checkPropTypes(
component.propTypes,
conformingProps,
'prop',
component.name);
expect(propError).toBeUndefined();
}
================================================
FILE: LEGACY-class-based-redux-components/jotto-redux-class-based/.gitignore
================================================
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*
================================================
FILE: LEGACY-class-based-redux-components/jotto-redux-class-based/README.md
================================================
# Jotto
### A React / Redux app used to demonstrate testing
## Branches
* `master`
This branch represents the project at the end of the instructional videos, without any of the challenges completed.
* `jotto-challenges`
[This branch](https://github.com/flyrightsister/udemy-react-testing-projects/tree/jotto-challenges/jotto) contains solutions to the challenges. You can also find challenge solutions in the [SOLUTIONS for Jotto Redux Challenges](https://github.com/flyrightsister/udemy-react-testing-projects/tree/master/SOLUTIONS%20for%20Jotto%20Redux%20Challenges) folder.
## Challenges
### 1. Number of Guesses

* _Note_: Try to accomplish this _without_ adding a new piece of state!
* Add “guess number” column to the "guessed words" table
* The first guess should show 1, second guess 2, etc.
* Add a component that displays total guesses as shown in wireframe
### 2. Reset Game

* Create a “New word” button component
* only display after successful guess
* Upon click, reset the game with a new word from the server
* _Note_: This can be done with a connected component (which lends itself to state testing similar to `Input.js`) or with an unconnected component which receives the action creator from the parent `App.js` component (which will require unit testing for action creators and reducers instead, as using a store with an unconnected component is not covered in this course). The solution in the `jotto-challenges` branch covers the second approach.
### 3. “Give up” Button


* Create a “Give up” button
* only display when word has not been guessed correctly
* Upon click:
* Show secret word
* Display "better luck next time" message
* Display “new word” button component
### 4. User inputs secret word


* _Note: This one is quite involved, with a new piece of state, Redux Thunk, and testing that an action creator receives the correct argument. Not for the faint of heart! It is great for using existing tests to see whether new code breaks old functionality._
* Add a button for the user to input the secret word
* This way, the user can play against a friend
* After submission, the game should use the user’s secret word, not a word from the server
* This button should disapppear once the user has nonzero `guessedWords`
* Should disappear whether the word came from the server or user input
### 5. Random Word Server Error

* Display an error if:
* There’s a problem contacting the “random word” server
* The server responds with status 4xx or 5xx
### 6. Use Wordnik to get secret word
* Get a [Wordnik auth token](http://developer.wordnik.com/)
* Use the [words/randomWord](http://developer.wordnik.com/docs.html) endpoint (instead of the random word server that came with this course)
## Credits
This project was bootstrapped with [Create React App](https://github.com/facebookincubator/create-react-app).
================================================
FILE: LEGACY-class-based-redux-components/jotto-redux-class-based/package.json
================================================
{
"name": "jotto",
"version": "0.1.0",
"private": true,
"dependencies": {
"axios": "^0.19.0",
"check-prop-types": "^1.1.2",
"enzyme": "^3.10.0",
"enzyme-adapter-react-16": "^1.14.0",
"jest-enzyme": "^7.1.1",
"moxios": "^0.4.0",
"prop-types": "^15.7.2",
"react": "^16.9.0",
"react-dom": "^16.9.0",
"react-redux": "^7.1.1",
"react-scripts": "3.1.1",
"redux": "^4.0.4",
"redux-thunk": "^2.3.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
================================================
FILE: LEGACY-class-based-redux-components/jotto-redux-class-based/public/index.html
================================================
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="theme-color" content="#000000">
<!--
manifest.json provides metadata used when your web app is added to the
homescreen on Android. See https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json">
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>
You need to enable JavaScript to run this app.
</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>
================================================
FILE: LEGACY-class-based-redux-components/jotto-redux-class-based/public/manifest.json
================================================
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
}
],
"start_url": "./index.html",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}
================================================
FILE: LEGACY-class-based-redux-components/jotto-redux-class-based/src/App.css
================================================
================================================
FILE: LEGACY-class-based-redux-components/jotto-redux-class-based/src/App.js
================================================
import React, { Component } from 'react';
import { connect } from 'react-redux';
import './App.css';
import GuessedWords from './GuessedWords';
import Congrats from './Congrats';
import Input from './Input';
import { getSecretWord } from './actions';
export class UnconnectedApp extends Component {
/**
* @method componentDidMount
* @returns {undefined}
*/
componentDidMount() {
// get the secret word
this.props.getSecretWord();
}
render() {
return (
<div className="container">
<h1>Jotto</h1>
<Congrats success={this.props.success} />
<Input />
<GuessedWords guessedWords={this.props.guessedWords} />
</div>
);
}
}
const mapStateToProps = (state) => {
const { success, guessedWords, secretWord } = state;
return { success, guessedWords, secretWord };
}
export default connect(mapStateToProps, { getSecretWord })(UnconnectedApp);
================================================
FILE: LEGACY-class-based-redux-components/jotto-redux-class-based/src/App.test.js
================================================
import React from 'react';
import { shallow } from 'enzyme';
import { storeFactory } from '../test/testUtils';
import App, { UnconnectedApp } from './App';
/**
* @function setup
* @param {object} state - State for this setup.
* @returns {ShallowWrapper}
*/
const setup = (state={}) => {
const store = storeFactory(state);
const wrapper = shallow(<App store={store} />).dive().dive();
return wrapper;
}
describe('redux properties', () => {
test('has access to `success` state', () => {
const success = true;
const wrapper = setup({ success });
const successProp = wrapper.instance().props.success;
expect(successProp).toBe(success);
});
test('has access to `secretWord` state', () => {
const secretWord = 'party';
const wrapper = setup({ secretWord });
const secretWordProp = wrapper.instance().props.secretWord;
expect(secretWordProp).toBe(secretWord);
});
test('has access to `guessedWords` state', () => {
const guessedWords = [{ guessedWord: 'train', letterMatchCount: 3 }];
const wrapper = setup({ guessedWords });
const guessedWordsProp = wrapper.instance().props.guessedWords;
expect(guessedWordsProp).toEqual(guessedWords);
});
test('`getSecretWord` action creator is a function on the props', () => {
const wrapper = setup();
const getSecretWordProp = wrapper.instance().props.getSecretWord;
expect(getSecretWordProp).toBeInstanceOf(Function);
});
});
test('`getSecretWord` runs on App mount', () => {
const getSecretWordMock = jest.fn();
const props = {
getSecretWord: getSecretWordMock,
success: false,
guessedWords: [],
}
// set up app component with getSecretWordMock as the getSecretWord prop
const wrapper = shallow(<UnconnectedApp {...props} />);
// run lifecycle method
wrapper.instance().componentDidMount();
// check to see if mock ran
const getSecretWordCallCount = getSecretWordMock.mock.calls.length;
expect(getSecretWordCallCount).toBe(1);
});
================================================
FILE: LEGACY-class-based-redux-components/jotto-redux-class-based/src/Congrats.js
================================================
import React from 'react';
import PropTypes from 'prop-types';
/**
* Functional react component for congratulatory message.
* @function
* @param {object} props - React props.
* @returns {JSX.Element} - Rendered component (or null if `success` prop is false).
*/
const Congrats = (props) => {
if (props.success) {
return (
<div data-test="component-congrats" className="alert alert-success">
<span data-test="congrats-message">
Congratulations! You guessed the word!
</span>
</div>
);
} else {
return (
<div data-test="component-congrats" />
);
}
};
Congrats.propTypes = {
success: PropTypes.bool.isRequired,
};
export default Congrats;
================================================
FILE: LEGACY-class-based-redux-components/jotto-redux-class-based/src/Congrats.test.js
================================================
import React from 'react';
import { shallow } from 'enzyme';
import { findByTestAttr, checkProps } from '../test/testUtils';
import Congrats from './Congrats';
const defaultProps = { success: false };
/**
* Factory function to create a ShallowWrapper for the Congrats component.
* @function setup
* @param {object} props - Component props specific to this setup.
* @returns {ShallowWrapper}
*/
const setup = (props={}) => {
const setupProps = { ...defaultProps, ...props };
return shallow(<Congrats {...setupProps} />)
}
test('renders without error', () => {
const wrapper = setup();
const component = findByTestAttr(wrapper, 'component-congrats');
expect(component.length).toBe(1);
});
test('renders no text when `success` prop is false', () => {
const wrapper = setup({ success: false });
const component = findByTestAttr(wrapper, 'component-congrats');
expect(component.text()).toBe('');
});
test('renders non-empty congrats message when `success` prop is true', () => {
const wrapper = setup({ success: true });
const message = findByTestAttr(wrapper, 'congrats-message');
expect(message.text().length).not.toBe(0);
});
test('does not throw warning with expected props', () => {
const expectedProps = { success: false };
checkProps(Congrats, expectedProps);
});
================================================
FILE: LEGACY-class-based-redux-components/jotto-redux-class-based/src/GuessedWords.js
================================================
import React from 'react';
import PropTypes from 'prop-types';
const GuessedWords = (props) => {
let contents
if (props.guessedWords.length === 0) {
contents = (
<span data-test="guess-instructions">
Try to guess the secret word!
</span>
);
} else {
const guessedWordsRows = props.guessedWords.map((word, index) => (
<tr data-test="guessed-word" key={ index }>
<td>{ word.guessedWord }</td>
<td>{ word.letterMatchCount }</td>
</tr>
));
contents = (
<div data-test="guessed-words">
<h3>Guessed Words</h3>
<table className="table table-sm">
<thead className="thead-light">
<tr><th>Guess</th><th>Matching Letters</th></tr>
</thead>
<tbody>
{ guessedWordsRows }
</tbody>
</table>
</div>
);
}
return (
<div data-test="component-guessed-words">
{ contents }
</div>
);
};
GuessedWords.propTypes = {
guessedWords: PropTypes.arrayOf(
PropTypes.shape({
guessedWord: PropTypes.string.isRequired,
letterMatchCount: PropTypes.number.isRequired,
})
).isRequired,
};
export default GuessedWords;
================================================
FILE: LEGACY-class-based-redux-components/jotto-redux-class-based/src/GuessedWords.test.js
================================================
import React from 'react';
import { shallow } from 'enzyme';
import { findByTestAttr, checkProps } from '../test/testUtils';
import GuessedWords from './GuessedWords';
const defaultProps = {
guessedWords: [{ guessedWord: 'train', letterMatchCount: 3 }],
};
/**
* Factory function to create a ShallowWrapper for the GuessedWords component.
* @function setup
* @param {object} props - Component props specific to this setup.
* @returns {ShallowWrapper}
*/
const setup = (props={}) => {
const setupProps = { ...defaultProps, ...props };
return shallow(<GuessedWords {...setupProps } />)
};
test('does not throw warning with expected props', () => {
checkProps(GuessedWords, defaultProps);
});
describe('if there are no words guessed', () => {
let wrapper
beforeEach(() => {
wrapper = setup({ guessedWords: [] });
});
test('renders without error', () => {
const component = findByTestAttr(wrapper, 'component-guessed-words');
expect(component.length).toBe(1);
});
test('renders instructions to guess a word', () => {
const instructions = findByTestAttr(wrapper, 'guess-instructions');
expect(instructions.text().length).not.toBe(0);
});
});
describe('if there are words guessed', () => {
let wrapper;
const guessedWords = [
{ guessedWord: 'train', letterMatchCount: 3 },
{ guessedWord: 'agile', letterMatchCount: 1 },
{ guessedWord: 'party', letterMatchCount: 5 },
];
beforeEach(() => {
wrapper = setup({ guessedWords });
});
test ('renders without error', () => {
const component = findByTestAttr(wrapper, 'component-guessed-words');
expect(component.length).toBe(1);
});
test('renders "guessed words" section', () => {
const guessedWordsNode = findByTestAttr(wrapper, 'guessed-words');
expect(guessedWordsNode.length).toBe(1);
});
test('correct number of guessed words', () => {
const guessedWordNodes = findByTestAttr(wrapper, 'guessed-word');
expect(guessedWordNodes.length).toBe(guessedWords.length);
});
});
================================================
FILE: LEGACY-class-based-redux-components/jotto-redux-class-based/src/Input.js
================================================
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { guessWord } from './actions';
export class UnconnectedInput extends Component {
/**
* @method constructor
* @param {object} props - Component props.
* @returns {undefined}
*/
constructor(props) {
super(props);
// initialize state
this.state = { currentGuess: null }
// bind this for submitGuessedWord
this.submitGuessedWord = this.submitGuessedWord.bind(this);
}
submitGuessedWord(evt) {
evt.preventDefault();
const guessedWord = this.state.currentGuess;
if(guessedWord && guessedWord.length > 0) {
this.props.guessWord(guessedWord);
this.setState({ currentGuess: '' })
}
}
render() {
const contents = this.props.success
? null
: (
<form className="form-inline">
<input
data-test="input-box"
className="mb-2 mx-sm-3"
id="word-guess"
type="text"
value={this.state.currentGuess}
onChange={(evt) => this.setState({ currentGuess: evt.target.value })}
placeholder="enter guess" />
<button
data-test="submit-button"
onClick={(evt) => this.submitGuessedWord(evt)}
className="btn btn-primary mb-2"
type="submit">
Submit
</button>
</form>
);
return (
<div data-test="component-input">
{ contents }
</div>
)
}
};
const mapStateToProps = ({ success }) => {
return { success };
}
export default connect(mapStateToProps, { guessWord })(UnconnectedInput);
================================================
FILE: LEGACY-class-based-redux-components/jotto-redux-class-based/src/Input.test.js
================================================
import React from 'react';
import { shallow } from 'enzyme';
import { findByTestAttr, storeFactory } from '../test/testUtils';
import Input, { UnconnectedInput } from './Input';
/**
* Factory function to create a ShallowWrapper for the Input component.
* @function setup
* @param {object} initialState - Initial state for this setup.
* @returns {ShallowWrapper}
*/
const setup = (initialState={}) => {
const store = storeFactory(initialState);
const wrapper = shallow(<Input store={store} />).dive().dive();
return wrapper;
}
describe('render', () => {
describe('word has not been guessed', () => {
let wrapper;
beforeEach(() => {
const initialState = { success: false };
wrapper = setup(initialState);
})
test('renders component without error', () => {
const component = findByTestAttr(wrapper, 'component-input');
expect(component.length).toBe(1);
});
test('renders input box', () => {
const inputBox = findByTestAttr(wrapper, 'input-box');
expect(inputBox.length).toBe(1);
});
test('renders submit button', () => {
const submitButton = findByTestAttr(wrapper, 'submit-button');
expect(submitButton.length).toBe(1);
});
});
describe('word has been guessed', () => {
let wrapper;
beforeEach(() => {
const initialState = { success: true };
wrapper = setup(initialState);
});
test('renders component without error', () => {
const component = findByTestAttr(wrapper, 'component-input');
expect(component.length).toBe(1);
});
test('does not render input box', () => {
const inputBox = findByTestAttr(wrapper, 'input-box');
expect(inputBox.length).toBe(0);
});
test('does not render submit button', () => {
const submit = findByTestAttr(wrapper, 'submit-button');
expect(submit.length).toBe(0);
});
});
});
describe('redux props', () => {
test('has success piece of state as prop', () => {
const success = true;
const wrapper = setup({ success });
const successProp = wrapper.instance().props.success;
expect(successProp).toBe(success);
});
test('`guessWord` action creator is a function prop', () => {
const wrapper = setup();
const guessWordProp = wrapper.instance().props.guessWord;
expect(guessWordProp).toBeInstanceOf(Function);
})
});
describe('`guessWord` action creator', () => {
let guessWordMock;
let wrapper;
const guessedWord = "train";
beforeEach(() => {
// create a mock function for `getSecretWord`
guessWordMock = jest.fn();
// set up Input, with guessWordMock as a prop
wrapper = shallow(<UnconnectedInput guessWord={guessWordMock} />);
// add value to input box
wrapper.setState({ currentGuess: guessedWord });
// simulate click on submit button
const submit = findByTestAttr(wrapper, 'submit-button');
submit.simulate('click', { preventDefault() {} });
});
test('`guessWord` was called once', () => {
const guessWordCallCount = guessWordMock.mock.calls.length;
expect(guessWordCallCount).toBe(1);
});
test('calls `guessWord with input value as argument`', () => {
const guessWordArg = guessWordMock.mock.calls[0][0];
expect(guessWordArg).toBe(guessedWord);
});
test('input box clears on submit', () => {
expect(wrapper.state('currentGuess')).toBe('');
})
});
================================================
FILE: LEGACY-class-based-redux-components/jotto-redux-class-based/src/actions/index.js
================================================
import axios from 'axios';
import { getLetterMatchCount } from '../helpers';
export const actionTypes = {
CORRECT_GUESS: 'CORRECT_GUESS',
GUESS_WORD: 'GUESS_WORD',
SET_SECRET_WORD: 'SET_SECRET_WORD',
};
/**
* Returns Redux Thunk function that dispatches GUESS_WORD action
* and (conditionally) CORRECT_GUESS action
* @function guessWord
* @param {string} guessedWord - Guessed word.
* @returns {function} - Redux Thunk function.
*/
export const guessWord = (guessedWord) => {
return function(dispatch, getState) {
const secretWord = getState().secretWord;
const letterMatchCount = getLetterMatchCount(guessedWord, secretWord);
dispatch({
type: actionTypes.GUESS_WORD,
payload: { guessedWord, letterMatchCount }
});
if (guessedWord === secretWord) {
dispatch({ type: actionTypes.CORRECT_GUESS });
}
};
};
/**
* Returns Redux Thunk function that initiates an axios request
* and dispatches the response as a 'SET_SECRET_WORD' action
* @returns {function} - Redux Thunk function.
*/
export const getSecretWord = () => {
return (dispatch) => {
return axios.get('http://localhost:3030')
.then(response => {
dispatch({
type: actionTypes.SET_SECRET_WORD,
payload: response.data
});
});
}
}
================================================
FILE: LEGACY-class-based-redux-components/jotto-redux-class-based/src/actions/index.test.js
================================================
import moxios from 'moxios';
import { storeFactory } from '../../test/testUtils';
import { getSecretWord } from './';
describe('getSecretWord action creator', () => {
beforeEach(() => {
moxios.install();
});
afterEach(() => {
moxios.uninstall();
});
test('adds response word to state', () => {
const secretWord = 'party';
const store = storeFactory();
moxios.wait(() => {
const request = moxios.requests.mostRecent();
request.respondWith({
status: 200,
response: secretWord,
});
});
return store.dispatch(getSecretWord())
.then(() => {
const newState = store.getState();
expect(newState.secretWord).toBe(secretWord);
})
});
});
================================================
FILE: LEGACY-class-based-redux-components/jotto-redux-class-based/src/configureStore.js
================================================
import { createStore, applyMiddleware } from 'redux';
import ReduxThunk from 'redux-thunk';
import rootReducer from './reducers';
export const middlewares = [ReduxThunk];
const createStoreWithMiddleware = applyMiddleware(...middlewares)(createStore);
export default createStoreWithMiddleware(rootReducer);
================================================
FILE: LEGACY-class-based-redux-components/jotto-redux-class-based/src/helpers/index.js
================================================
/**
* @method getLetterMatchCount
* @param {string} guessedWord - Guessed word.
* @param {string} secretWord - Secret word.
* @returns {number} - Number of letters matched between guessed word and secret word.
*/
export function getLetterMatchCount(guessedWord, secretWord) {
const secretLetters = secretWord.split('');
const guessedLetterSet = new Set(guessedWord);
return secretLetters.filter(letter => guessedLetterSet.has(letter)).length;
};
================================================
FILE: LEGACY-class-based-redux-components/jotto-redux-class-based/src/helpers/index.test.js
================================================
import { getLetterMatchCount } from './';
describe('getLetterMatchCount', () => {
const secretWord = 'party';
test('returns correct count when there are no matching letters', () => {
const letterMatchCount = getLetterMatchCount('bones', secretWord);
expect(letterMatchCount).toBe(0);
});
test('returns the correct count where there are 3 matching letters', () => {
const letterMatchCount = getLetterMatchCount('train', secretWord);
expect(letterMatchCount).toBe(3);
});
test('returns correct count when there are duplicate letters in the guess', () => {
const letterMatchCount = getLetterMatchCount('parka', secretWord);
expect(letterMatchCount).toBe(3);
});
});
================================================
FILE: LEGACY-class-based-redux-components/jotto-redux-class-based/src/index.css
================================================
body {
margin: 0;
padding: 0;
font-family: sans-serif;
}
================================================
FILE: LEGACY-class-based-redux-components/jotto-redux-class-based/src/index.js
================================================
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import store from './configureStore';
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root'));
registerServiceWorker();
================================================
FILE: LEGACY-class-based-redux-components/jotto-redux-class-based/src/integration.test.js
================================================
import { storeFactory } from '../test/testUtils';
import { guessWord } from './actions';
describe('guessWord action dispatcher', () => {
const secretWord = 'party';
const unsuccessfulGuess = 'train';
describe('no guessed words', () => {
let store;
const initialState = { secretWord };
beforeEach(() => {
store = storeFactory(initialState);
});
test('updates state correctly for unsuccessful guess', () => {
store.dispatch(guessWord(unsuccessfulGuess));
const newState = store.getState()
const expectedState = {
...initialState,
success: false,
guessedWords: [{
guessedWord: unsuccessfulGuess,
letterMatchCount: 3
}]
};
expect(newState).toEqual(expectedState);
});
test('updates state correctly for successful guess', () => {
store.dispatch(guessWord(secretWord));
const newState = store.getState()
const expectedState = {
secretWord,
success: true,
guessedWords: [{
guessedWord: secretWord,
letterMatchCount: 5,
}],
};
expect(newState).toEqual(expectedState);
});
});
describe('some guessed words', () => {
const guessedWords = [ { guessedWord: 'agile', letterMatchCount: 1 } ];
const initialState = { guessedWords, secretWord }
let store;
beforeEach(() => {
store = storeFactory(initialState);
})
test('updates state correctly for unsuccessful guess', () => {
store.dispatch(guessWord(unsuccessfulGuess));
const newState = store.getState();
const expectedState = {
secretWord,
success: false,
guessedWords: [...guessedWords, { guessedWord: unsuccessfulGuess, letterMatchCount: 3 }]
};
expect(newState).toEqual(expectedState);
});
test('updates state correctly for successful guess', () => {
store.dispatch(guessWord(secretWord));
const newState = store.getState();
const expectedState = {
secretWord,
success: true,
guessedWords: [...guessedWords,
{ guessedWord: secretWord, letterMatchCount: 5 }]
};
expect(newState).toEqual(expectedState);
});
});
});
================================================
FILE: LEGACY-class-based-redux-components/jotto-redux-class-based/src/reducers/guessedWordsReducer.js
================================================
import { actionTypes } from '../actions';
/**
* @function guessedWordsReducer
* @param {array} state - Array of guessed words.
* @param {object} action - action to be reduced.
* @returns {array} - new guessedWords state.
*/
export default (state=[], action) => {
switch(action.type) {
case actionTypes.GUESS_WORD:
return [...state, action.payload];
default:
return state;
}
}
================================================
FILE: LEGACY-class-based-redux-components/jotto-redux-class-based/src/reducers/index.js
================================================
import { combineReducers } from 'redux';
import success from './successReducer';
import guessedWords from './guessedWordsReducer';
import secretWord from './secretWordReducer';
export default combineReducers({
success,
guessedWords,
secretWord,
});
================================================
FILE: LEGACY-class-based-redux-components/jotto-redux-class-based/src/reducers/secretWordReducer.js
================================================
import { actionTypes } from '../actions';
/**
* @function secretWordReducer
* @param {string} state - State before reducer.
* @param {object} action - Action sent to reducer.
* @returns {string} - New state (secret word payload from action).
*/
export default (state=null, action) => {
switch (action.type) {
case actionTypes.SET_SECRET_WORD:
return action.payload;
default:
return state;
}
}
================================================
FILE: LEGACY-class-based-redux-components/jotto-redux-class-based/src/reducers/successReducer.js
================================================
import { actionTypes } from '../actions';
/**
* @function successReducer
* @param {array} state - Array of guessed words.
* @param {object} action - action to be reduced.
* @returns {boolean} - new success state.
*/
export default (state=false, action) => {
switch(action.type) {
case (actionTypes.CORRECT_GUESS):
return true;
default:
return state;
}
}
================================================
FILE: LEGACY-class-based-redux-components/jotto-redux-class-based/src/reducers/successReducer.test.js
================================================
import { actionTypes } from '../actions';
import successReducer from './successReducer';
test('returns default initial state of `false` when no action is passed', () => {
const newState = successReducer(undefined, {});
expect(newState).toBe(false);
});
test('returns state of true upon receiving an action of type `CORRECT_GUESS`', () => {
const newState = successReducer(undefined, { type: actionTypes.CORRECT_GUESS });
expect(newState).toBe(true);
});
================================================
FILE: LEGACY-class-based-redux-components/jotto-redux-class-based/src/registerServiceWorker.js
================================================
// In production, we register a service worker to serve assets from local cache.
// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on the "N+1" visit to a page, since previously
// cached resources are updated in the background.
// To learn more about the benefits of this model, read https://goo.gl/KwvDNy.
// This link also includes instructions on opting out of this behavior.
const isLocalhost = Boolean(
window.location.hostname === 'localhost' ||
// [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' ||
// 127.0.0.1/8 is considered localhost for IPv4.
window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
)
);
export default function register() {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(process.env.PUBLIC_URL, window.location);
if (publicUrl.origin !== window.location.origin) {
// Our service worker won't work if PUBLIC_URL is on a different origin
// from what our page is served on. This might happen if a CDN is used to
// serve assets; see https://github.com/facebookincubator/create-react-app/issues/2374
return;
}
window.addEventListener('load', () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
if (isLocalhost) {
// This is running on localhost. Lets check if a service worker still exists or not.
checkValidServiceWorker(swUrl);
// Add some additional logging to localhost, pointing developers to the
// service worker/PWA documentation.
navigator.serviceWorker.ready.then(() => {
console.log(
'This web app is being served cache-first by a service ' +
'worker. To learn more, visit https://goo.gl/SC7cgQ'
);
});
} else {
// Is not local host. Just register service worker
registerValidSW(swUrl);
}
});
}
}
function registerValidSW(swUrl) {
navigator.serviceWorker
.register(swUrl)
.then(registration => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point, the old content will have been purged and
// the fresh content will have been added to the cache.
// It's the perfect time to display a "New content is
// available; please refresh." message in your web app.
console.log('New content is available; please refresh.');
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log('Content is cached for offline use.');
}
}
};
};
})
.catch(error => {
console.error('Error during service worker registration:', error);
});
}
function checkValidServiceWorker(swUrl) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl)
.then(response => {
// Ensure service worker exists, and that we really are getting a JS file.
if (
response.status === 404 ||
response.headers.get('content-type').indexOf('javascript') === -1
) {
// No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then(registration => {
registration.unregister().then(() => {
window.location.reload();
});
});
} else {
// Service worker found. Proceed as normal.
registerValidSW(swUrl);
}
})
.catch(() => {
console.log(
'No internet connection found. App is running in offline mode.'
);
});
}
export function unregister() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready.then(registration => {
registration.unregister();
});
}
}
================================================
FILE: LEGACY-class-based-redux-components/jotto-redux-class-based/src/setupTests.js
================================================
import Enzyme, { shallow } from 'enzyme';
import EnzymeAdapter from 'enzyme-adapter-react-16';
Enzyme.configure({
adapter: new EnzymeAdapter(),
disableLifecycleMethods: true,
});
================================================
FILE: LEGACY-class-based-redux-components/jotto-redux-class-based/test/testUtils.js
================================================
import checkPropTypes from 'check-prop-types';
import { createStore, applyMiddleware } from 'redux';
import rootReducer from '../src/reducers';
import { middlewares } from '../src/configureStore';
/**
* Create a testing store with imported reducers, middleware, and initial state.
* globals: rootReducer, middlewares.
* @param {object} initialState - Initial state for store.
* @function storeFactory
* @returns {Store} - Redux store.
*/
export const storeFactory = (initialState) => {
const createStoreWithMiddleware = applyMiddleware(...middlewares)(createStore)
return createStoreWithMiddleware(rootReducer, initialState);
}
/**
* Return node(s) with the given data-test attribute.
* @param {ShallowWrapper} wrapper - Enzyme shallow wrapper.
* @param {string} val - Value of data-test attribute for search.
* @returns {ShallowWrapper}
*/
export const findByTestAttr = (wrapper, val) => {
return wrapper.find(`[data-test="${val}"]`);
}
export const checkProps = (component, conformingProps) => {
const propError = checkPropTypes(
component.propTypes,
conformingProps,
'prop',
component.name);
expect(propError).toBeUndefined();
}
================================================
FILE: README.md
================================================
# udemy-ENZYME
Code for projects presented in Udemy [React Testing with Jest and Enzyme](https://www.udemy.com/course/react-testing-with-jest-and-enzyme/?couponCode=ENZYME-GITHUB) course
================================================
FILE: SOLUTIONS for Click Counter Challenges/.gitignore
================================================
# See https://help.github.com/ignore-files/ for more about ignoring files.
# dependencies
/node_modules
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*
================================================
FILE: SOLUTIONS for Click Counter Challenges/.npmrc
================================================
fund=false
audit=false
loglevel=error
================================================
FILE: SOLUTIONS for Click Counter Challenges/README.md
================================================
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
In the project directory, you can run:
### `npm start`
Runs the app in the development mode.<br />
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
The page will reload if you make edits.<br />
You will also see any lint errors in the console.
### `npm test`
Launches the test runner in the interactive watch mode.<br />
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `npm run build`
Builds the app for production to the `build` folder.<br />
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.<br />
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `npm run eject`
**Note: this is a one-way operation. Once you `eject`, you can’t go back!**
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.
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.
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.
## Learn More
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
To learn React, check out the [React documentation](https://reactjs.org/).
### Code Splitting
This section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting
### Analyzing the Bundle Size
This section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size
### Making a Progressive Web App
This section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app
### Advanced Configuration
This section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration
### Deployment
This section has moved here: https://facebook.github.io/create-react-app/docs/deployment
### `npm run build` fails to minify
This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify
================================================
FILE: SOLUTIONS for Click Counter Challenges/package.json
================================================
{
"name": "click-counter-functional",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^4.2.4",
"@testing-library/react": "^9.5.0",
"@testing-library/user-event": "^7.2.1",
"enzyme": "^3.11.0",
"enzyme-adapter-react-16": "^1.15.2",
"jest-enzyme": "^7.1.2",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-scripts": "3.4.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
================================================
FILE: SOLUTIONS for Click Counter Challenges/public/index.html
================================================
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>
================================================
FILE: SOLUTIONS for Click Counter Challenges/public/manifest.json
================================================
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
},
{
"src": "logo192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "logo512.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}
================================================
FILE: SOLUTIONS for Click Counter Challenges/public/robots.txt
================================================
# https://www.robotstxt.org/robotstxt.html
User-agent: *
Disallow:
================================================
FILE: SOLUTIONS for Click Counter Challenges/src/App.css
================================================
.App {
text-align: center;
}
.App-logo {
height: 40vmin;
pointer-events: none;
}
@media (prefers-reduced-motion: no-preference) {
.App-logo {
animation: App-logo-spin infinite 20s linear;
}
}
.App-header {
background-color: #282c34;
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: calc(10px + 2vmin);
color: white;
}
.App-link {
color: #61dafb;
}
@keyframes App-logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
/* error styling for challenge #2 */
.error {
font-size: 150%;
color: red;
}
/* for challenge #2 and #3 to show / hide error message */
.hidden {
display: none;
}
================================================
FILE: SOLUTIONS for Click Counter Challenges/src/App.js
================================================
import React from 'react';
import logo from './logo.svg';
import './App.css';
function App() {
const [count, setCount] = React.useState(0);
const [error, setError] = React.useState(false);
return (
<div data-test="component-app" className="App">
<h1 data-test="counter-display">
The counter is currently
<span data-test="count">{count}</span>
</h1>
{/* Notes:
- using ternary on the error state to determine whether or not to hide
- the 'error' and 'hidden' classes are defined in App.css
*/}
<div data-test="error-message" className={`error ${error ? '' : 'hidden'}`}>
The counter cannot go below 0
</div>
<button
data-test="increment-button"
onClick={() => {
if (error) { setError(false); }
setCount(count + 1)
}
}
>
Increment counter
</button>
<button
data-test="decrement-button"
onClick={() => {
if (count > 0) {
setCount(count - 1)
} else {
setError(true);
}
}
}
>
Decrement counter
</button>
</div>
);
}
export default App;
================================================
FILE: SOLUTIONS for Click Counter Challenges/src/App.test.js
================================================
import React from "react";
import Enzyme, { shallow } from "enzyme";
import EnzymeAdapter from "enzyme-adapter-react-16";
import App from "./App";
Enzyme.configure({ adapter: new EnzymeAdapter() });
/**
* Factory function to create a ShallowWrapper for the App component.
* @function setup
* @param {object} props - Component props specific to this setup.
* @returns {ShallowWrapper}
*/
const setup = (props = {}) => {
return shallow(<App {...props} />);
};
/**
* Return ShallowWrapper containing node(s) with the given data-test value.
* @param {ShallowWrapper} wrapper - Enzyme shallow wrapper to search within.
* @param {string} val - Value of data-test c1scoL0ve!
*
*/
const findByTestAttr = (wrapper, val) => {
return wrapper.find(`[data-test="${val}"]`);
};
test("renders without error", () => {
const wrapper = setup();
const appComponent = findByTestAttr(wrapper, "component-app");
expect(appComponent.length).toBe(1);
});
test("renders counter display", () => {
const wrapper = setup();
const counterDisplay = findByTestAttr(wrapper, "counter-display");
expect(counterDisplay.length).toBe(1);
});
test("counter starts at 0", () => {
const wrapper = setup();
const count = findByTestAttr(wrapper, "count").text();
expect(count).toBe("0"); // do this first with an integer and show failure!
});
describe("Increment", () => {
// now we have enough tests to organize by function
test("renders increment button", () => {
const wrapper = setup();
const button = findByTestAttr(wrapper, "increment-button");
expect(button.length).toBe(1);
});
test("counter increments when button is clicked", () => {
const wrapper = setup();
// find button and click
const button = findByTestAttr(wrapper, "increment-button");
button.simulate("click");
// check the counter
const count = findByTestAttr(wrapper, "count").text();
expect(count).toBe("1");
});
});
describe("decrement button", () => {
test("renders decrement button", () => {
const wrapper = setup();
const button = findByTestAttr(wrapper, "decrement-button");
expect(button.length).toBe(1);
});
test("clicking decrement button decrements counter display when state is greater than 0", () => {
const wrapper = setup();
// click the increment button so that the counter is greater than 0
const incButton = findByTestAttr(wrapper, "increment-button");
incButton.simulate("click");
// find decrement button and click
const decButton = findByTestAttr(wrapper, "decrement-button");
decButton.simulate("click");
// find display and test value
const count = findByTestAttr(wrapper, "count").text();
expect(count).toBe("0");
});
});
describe("error when counter goes below 0", () => {
test("error does not show when not needed", () => {
// I plan to implement this by using a "hidden" class for the error div
// I plan to use the data-test value 'error-message' for the error div
const wrapper = setup();
const errorDiv = findByTestAttr(wrapper, "error-message");
// using enzyme's ".hasClass()" method
// http://airbnb.io/enzyme/docs/api/ShallowWrapper/hasClass.html
const errorHasHiddenClass = errorDiv.hasClass("hidden");
expect(errorHasHiddenClass).toBe(true);
});
describe("counter is 0 and decrement is clicked", () => {
// using a describe here so I can use a "beforeEach" for shared setup
// scoping wrapper to the describe, so it can be used in beforeEach and the tests
let wrapper;
beforeEach(() => {
// no need to set counter value here; default value of 0 is good
wrapper = setup();
// find button and click
const button = findByTestAttr(wrapper, "decrement-button");
button.simulate("click");
});
test("error shows", () => {
// check the class of the error message
const errorDiv = findByTestAttr(wrapper, "error-message");
const errorHasHiddenClass = errorDiv.hasClass("hidden");
expect(errorHasHiddenClass).toBe(false);
});
test("counter still displays 0", () => {
const count = findByTestAttr(wrapper, "count").text();
expect(count).toBe("0");
});
test("clicking increment clears the error", () => {
// find and click the increment button
const incButton = findByTestAttr(wrapper, "increment-button");
incButton.simulate("click");
// check the class of the error message
const errorDiv = findByTestAttr(wrapper, "error-message");
const errorHasHiddenClass = errorDiv.hasClass("hidden");
expect(errorHasHiddenClass).toBe(true);
});
});
});
================================================
FILE: SOLUTIONS for Click Counter Challenges/src/index.css
================================================
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
}
================================================
FILE: SOLUTIONS for Click Counter Challenges/src/index.js
================================================
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();
================================================
FILE: SOLUTIONS for Click Counter Challenges/src/registerServiceWorker.js
================================================
// In production, we register a service worker to serve assets from local cache.
// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on the "N+1" visit to a page, since previously
// cached resources are updated in the background.
// To learn more about the benefits of this model, read https://goo.gl/KwvDNy.
// This link also includes instructions on opting out of this behavior.
const isLocalhost = Boolean(
window.location.hostname === 'localhost' ||
// [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' ||
// 127.0.0.1/8 is considered localhost for IPv4.
window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
)
);
export default function register() {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(process.env.PUBLIC_URL, window.location);
if (publicUrl.origin !== window.location.origin) {
// Our service worker won't work if PUBLIC_URL is on a different origin
// from what our page is served on. This might happen if a CDN is used to
// serve assets; see https://github.com/facebookincubator/create-react-app/issues/2374
return;
}
window.addEventListener('load', () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
if (isLocalhost) {
// This is running on localhost. Lets check if a service worker still exists or not.
checkValidServiceWorker(swUrl);
// Add some additional logging to localhost, pointing developers to the
// service worker/PWA documentation.
navigator.serviceWorker.ready.then(() => {
console.log(
'This web app is being served cache-first by a service ' +
'worker. To learn more, visit https://goo.gl/SC7cgQ'
);
});
} else {
// Is not local host. Just register service worker
registerValidSW(swUrl);
}
});
}
}
function registerValidSW(swUrl) {
navigator.serviceWorker
.register(swUrl)
.then(registration => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point, the old content will have been purged and
// the fresh content will have been added to the cache.
// It's the perfect time to display a "New content is
// available; please refresh." message in your web app.
console.log('New content is available; please refresh.');
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log('Content is cached for offline use.');
}
}
};
};
})
.catch(error => {
console.error('Error during service worker registration:', error);
});
}
function checkValidServiceWorker(swUrl) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl)
.then(response => {
// Ensure service worker exists, and that we really are getting a JS file.
if (
response.status === 404 ||
response.headers.get('content-type').indexOf('javascript') === -1
) {
// No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then(registration => {
registration.unregister().then(() => {
window.location.reload();
});
});
} else {
// Service worker found. Proceed as normal.
registerValidSW(swUrl);
}
})
.catch(() => {
console.log(
'No internet connection found. App is running in offline mode.'
);
});
}
export function unregister() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready.then(registration => {
registration.unregister();
});
}
}
================================================
FILE: SOLUTIONS for Click Counter Challenges/src/serviceWorker.js
================================================
// This optional code is used to register a service worker.
// register() is not called by default.
// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on subsequent visits to a page, after all the
// existing tabs open on the page have been closed, since previously cached
// resources are updated in the background.
// To learn more about the benefits of this model and instructions on how to
// opt-in, read https://bit.ly/CRA-PWA
const isLocalhost = Boolean(
window.location.hostname === 'localhost' ||
// [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' ||
// 127.0.0.0/8 are considered localhost for IPv4.
window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
)
);
export function register(config) {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
if (publicUrl.origin !== window.location.origin) {
// Our service worker won't work if PUBLIC_URL is on a different origin
// from what our page is served on. This might happen if a CDN is used to
// serve assets; see https://github.com/facebook/create-react-app/issues/2374
return;
}
window.addEventListener('load', () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
if (isLocalhost) {
// This is running on localhost. Let's check if a service worker still exists or not.
checkValidServiceWorker(swUrl, config);
// Add some additional logging to localhost, pointing developers to the
// service worker/PWA documentation.
navigator.serviceWorker.ready.then(() => {
console.log(
'This web app is being served cache-first by a service ' +
'worker. To learn more, visit https://bit.ly/CRA-PWA'
);
});
} else {
// Is not localhost. Just register service worker
registerValidSW(swUrl, config);
}
});
}
}
function registerValidSW(swUrl, config) {
navigator.serviceWorker
.register(swUrl)
.then(registration => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
if (installingWorker == null) {
return;
}
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point, the updated precached content has been fetched,
// but the previous service worker will still serve the older
// content until all client tabs are closed.
console.log(
'New content is available and will be used when all ' +
'tabs for this page are closed. See https://bit.ly/CRA-PWA.'
);
// Execute callback
if (config && config.onUpdate) {
config.onUpdate(registration);
}
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log('Content is cached for offline use.');
// Execute callback
if (config && config.onSuccess) {
config.onSuccess(registration);
}
}
}
};
};
})
.catch(error => {
console.error('Error during service worker registration:', error);
});
}
function checkValidServiceWorker(swUrl, config) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl, {
headers: { 'Service-Worker': 'script' },
})
.then(response => {
// Ensure service worker exists, and that we really are getting a JS file.
const contentType = response.headers.get('content-type');
if (
response.status === 404 ||
(contentType != null && contentType.indexOf('javascript') === -1)
) {
// No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then(registration => {
registration.unregister().then(() => {
window.location.reload();
});
});
} else {
// Service worker found. Proceed as normal.
registerValidSW(swUrl, config);
}
})
.catch(() => {
console.log(
'No internet connection found. App is running in offline mode.'
);
});
}
export function unregister() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready
.then(registration => {
registration.unregister();
})
.catch(error => {
console.error(error.message);
});
}
}
================================================
FILE: SOLUTIONS for Click Counter Challenges/src/setupTests.js
================================================
// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom/extend-expect';
================================================
FILE: SOLUTIONS for Jotto Context Challenges/.npmrc
================================================
fund=false
audit=false
loglevel=error
================================================
FILE: SOLUTIONS for Jotto Context Challenges/README.md
================================================
# Jotto
### A React app with hooks and contexts used to demonstrate testing
## Branches
* `master`
This branch represents the project at the end of the instructional videos, without any of the challenges completed.
* `jotto-hooks-challenges`
[This branch](https://github.com/flyrightsister/udemy-react-testing-projects/tree/jotto-challenges/jotto) contains solutions to the challenges.
## Challenges
### 1. Number of Guesses

* _Note_: Try to accomplish this _without_ adding a new piece of state!
* Add “guess number” column to the "guessed words" table
* The first guess should show 1, second guess 2, etc.
* Add a component that displays total guesses as shown in wireframe
### 2. Reset Game

* Create a “New word” button component
* only display after successful guess
* Upon click, reset the game with a new word from the server
* _Notes_: This one is going to need access to `setGuessedWords` and `setSuccess` to reset those pieces of state upon click. It can import `getSecretWord` from `actions/hookActions`, but it will need `setSecretWord` from `App.js` to pass as a callback to `getSecretWord`. I recommend passing `setSecretWord` as a prop.
To test which components show up
after clicking the New Word Button, try running `mount` on `App` after you've mocked
`hookActions.getSecretWord` to run the callback function
argument with the secretWord value (to avoid making a
network call when `App` mounts). For example:
```
hookActions.getSecretWord = jest.fn(setSecretWord => setSecretWord('party'));
```
Then you can find and click the new word button and test to see the state of various components. You might make a new integration test file for this, or you could keep these tests within NewWordButton.test.js -- your choice.
### 3. “Give up” Button


* Create a “Give up” button
* only display when word has not been guessed correctly
* Upon click:
* Show secret word
* Display "better luck next time" message
* Display “new word” button component
* Set `success` context to `true` (the other components should display as though `success` is true; that is, no Input and show New Word button. The exception is Congrats of course!)
* _Note_: This one is quite involved! One way to approach it: Update
the `App` component to have `givenUp` as part of its state,
and then display components depending on the values of
`givenUp` and `success`.
You will also need to
update the `NewWordButton` onClick to reset `givenUp`.
You can use the same method to check on components after click as you did with Challenge #2.
### 4. User inputs secret word


* Add a button for the user to input the secret word
* This way, the user can play against a friend
* After submission, the game should use the user’s secret word, not a word from the server
* This button should disapppear once the user has nonzero `guessedWords`
* _Note: The entry form is another chance to practice with a state-controlled field._
### 5. Random Word Server Error

* Display an error if:
* There’s a problem contacting the “random word” server
* The server responds with status 4xx or 5xx
## Credits
This project was bootstrapped with [Create React App](https://github.com/facebookincubator/create-react-app).
================================================
FILE: SOLUTIONS for Jotto Context Challenges/package.json
================================================
{
"name": "jotto-hooks",
"version": "0.1.0",
"private": true,
"dependencies": {
"axios": "^0.19.0",
"prop-types": "^15.7.2",
"react": "^16.9.0",
"react-dom": "^16.9.0",
"react-scripts": "3.1.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"check-prop-types": "^1.1.2",
"enzyme": "^3.10.0",
"enzyme-adapter-react-16": "^1.14.0",
"jest-enzyme": "^7.1.0",
"moxios": "^0.4.0"
}
}
================================================
FILE: SOLUTIONS for Jotto Context Challenges/public/index.html
================================================
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js" integrity="sha384-xrRywqdh3PHs8keKZN+8zzc5TX0GRTLCcmivcbNJWm2rs5C8PRhcEn3czEjhAO9o" crossorigin="anonymous"></script>
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>
================================================
FILE: SOLUTIONS for Jotto Context Challenges/public/manifest.json
================================================
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
},
{
"src": "logo192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "logo512.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}
================================================
FILE: SOLUTIONS for Jotto Context Challenges/public/robots.txt
================================================
# https://www.robotstxt.org/robotstxt.html
User-agent: *
================================================
FILE: SOLUTIONS for Jotto Context Challenges/src/App.css
================================================
.App {
text-align: center;
}
.App-logo {
animation: App-logo-spin infinite 20s linear;
height: 40vmin;
pointer-events: none;
}
.App-header {
background-color: #282c34;
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: calc(10px + 2vmin);
color: white;
}
.App-link {
color: #61dafb;
}
@keyframes App-logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
================================================
FILE: SOLUTIONS for Jotto Context Challenges/src/App.js
================================================
import React from 'react';
import './App.css';
import hookActions from './actions/hookActions';
import languageContext from './contexts/languageContext';
import successContext from './contexts/successContext';
import guessedWordsContext from './contexts/guessedWordsContext';
import LanguagePicker from './LanguagePicker';
import Input from './Input';
import Congrats from './Congrats';
import GuessedWords from './GuessedWords';
import NewWordButton from './NewWordButton';
import SecretWordReveal from './SecretWordReveal';
import GiveUpButton from './GiveUpButton';
import EnterSecretWordButton from './EnterSecretWordButton';
import SecretWordEntry from './SecretWordEntry';
/**
* Reducer to update state, called automatically by dispatch
* @param state {object} - existing state
* @param action {object} - contains 'type' and 'payload' properties for the state update
* for example: { type: "setSecretWord", payload: "party" }
* @return {object} - new state
*/
function reducer(state, action) {
switch(action.type) {
case "setSecretWord":
return { ...state, secretWord: action.payload };
case "setLanguage":
return { ...state, language: action.payload };
// Challenge #3: Give Up
case "setGivenUp":
return { ...state, givenUp: action.payload }
// END: Challenge #3: Give Up
// Challenge #4: Enter Secret Word
case "setEnterSecretWord":
return { ...state, enterSecretWord: action.payload }
// END: Challenge #4: Enter Secret Word
// Challenge #5: Server Error
case "setServerError":
return { ...state, serverError: action.payload }
// END: Challenge #5: Server Error
default:
throw new Error(`Invalid action type: ${action.type}`);
}
}
function App() {
const [state, dispatch] = React.useReducer(
reducer,
{ secretWord: null, language: 'en' }
)
const setSecretWord = (secretWord) =>
dispatch({ type: "setSecretWord", payload: secretWord });
const setLanguage = (language) =>
dispatch({ type: "setLanguage", payload: language });
// Challenge #3: Give Up
const setGivenUp = (givenUp) =>
dispatch({ type: "setGivenUp", payload: givenUp })
// END: Challenge #3: Give Up
// Challenge #4: Enter Secret Word
const setEnterSecretWord = (enterSecretWord) =>
dispatch({ type: "setEnterSecretWord", payload: enterSecretWord })
// END: Challenge #4: Enter Secret Word
// Challenge #5: Server Error
const setServerError = (isServerError) =>
dispatch({ type: "setEnterSecretWord", payload: isServerError })
// END: Challenge #5: Server Error
React.useEffect(
() => { hookActions.getSecretWord(setSecretWord, setServerError) },
[]
)
if(!state.secretWord) {
return (
<div className="container" data-test="spinner">
<div className="spinner-border" role="status">
<span className="sr-only">Loading...</span>
</div>
<p>Loading secret word</p>
</div>
);
}
return (
<div className="container" data-test="component-app">
<h1>Jotto</h1>
<languageContext.Provider value={state.language}>
<LanguagePicker setLanguage={setLanguage} />
<guessedWordsContext.GuessedWordsProvider>
{/* Challenge #5: Server Error */}
{/* Challenge #4: Enter Secret Word */}
{ state.enterSecretWord
? <SecretWordEntry setEnterSecretWord={setEnterSecretWord} setSecretWord={setSecretWord} />
: (<div>
<successContext.SuccessProvider>
{/* Challenge #3: Give Up */}
{ state.givenUp
? <SecretWordReveal secretWord={state.secretWord}/>
: <Congrats /> }
{/* END: Challenge #3: Give Up */}
{/* Challenge #2 and #3 */}
<NewWordButton setSecretWord={setSecretWord} setGivenUp={setGivenUp} />
{ !state.givenUp ? <GiveUpButton setGivenUp={setGivenUp}/> : "" }
<Input secretWord={state.secretWord} />
{/* END: Challenge #2 and #3 */}
</successContext.SuccessProvider>
<GuessedWords />
<EnterSecretWordButton setEnterSecretWord={setEnterSecretWord} />
</div>)
}
{/* END: Challenge #4: Enter Secret Word */}
{/* END: Challenge #5: Server Error */}
</guessedWordsContext.GuessedWordsProvider>
</languageContext.Provider>
</div>
);
}
export default App;
================================================
FILE: SOLUTIONS for Jotto Context Challenges/src/App.test.js
================================================
import React from 'react';
import { mount } from 'enzyme';
import { findByTestAttr } from '../test/testUtils';
import App from './App';
import hookActions from './actions/hookActions';
const mockGetSecretWord = jest.fn();
/**
* Setup function for app component.
* @param {string} secretWord - desired secretWord state value for test
* @returns {ReactWrapper}
*/
const setup = (secretWord="party") => {
mockGetSecretWord.mockClear();
hookActions.getSecretWord = mockGetSecretWord;
const mockUseReducer = jest.fn()
.mockReturnValue([
{ secretWord, language: 'en' },
jest.fn()
]);
React.useReducer = mockUseReducer;
// use mount, because useEffect not called on `shallow`
// https://github.com/airbnb/enzyme/issues/2086
return mount(<App />);
}
test('App renders without error', () => {
const wrapper = setup();
const component = findByTestAttr(wrapper, 'component-app');
expect(component.length).toBe(1);
});
describe('getSecretWord calls', () => {
test('getSecretWord gets called on App mount', () => {
setup();
// check to see if secret word was updated
expect(mockGetSecretWord).toHaveBeenCalled();
});
test('secretWord does not update on App update', () => {
const wrapper = setup();
mockGetSecretWord.mockClear();
// wrapper.update() doesn't trigger update
// (issue forked from https://github.com/airbnb/enzyme/issues/2091)
wrapper.setProps();
expect(mockGetSecretWord).not.toHaveBeenCalled();
});
});
describe("secretWord is not null", () => {
let wrapper;
beforeEach(() => {
wrapper = setup("party");
});
test("renders app when secretWord is not null", () => {
const appComponent = findByTestAttr(wrapper, "component-app");
expect(appComponent.exists()).toBe(true);
});
test("does not render spinner when secretWord is not null", () => {
const spinnerComponent = findByTestAttr(wrapper, "spinner");
expect(spinnerComponent.exists()).toBe(false);
});
});
describe("secretWord is null", () => {
let wrapper;
beforeEach(() => {
wrapper = setup(null);
});
test("does not render app when secretWord is null", () => {
const appComponent = findByTestAttr(wrapper, "component-app");
expect(appComponent.exists()).toBe(false);
});
test("renders spinner when secretWord is null", () => {
const spinnerComponent = findByTestAttr(wrapper, "spinner");
expect(spinnerComponent.exists()).toBe(true);
});
});
================================================
FILE: SOLUTIONS for Jotto Context Challenges/src/Congrats.js
================================================
import React from 'react';
import successContext from './contexts/successContext';
import languageContext from './contexts/languageContext';
import stringsModule from './helpers/strings';
/**
* Functional react component for congratulatory message.
* @function
* @returns {JSX.Element} - Rendered component (or null if `success` prop is false).
*/
const Congrats = () => {
const [success] = successContext.useSuccess();
const language = React.useContext(languageContext);
if (success) {
return (
<div data-test="component-congrats" className="alert alert-success">
<span data-test="congrats-message">
{stringsModule.getStringByLanguage(language, 'congrats')}
</span>
</div>
);
} else {
return (
<div data-test="component-congrats" />
);
}
};
export default Congrats;
================================================
FILE: SOLUTIONS for Jotto Context Challenges/src/Congrats.test.js
================================================
import React from 'react';
import { mount } from 'enzyme';
import { findByTestAttr } from '../test/testUtils';
import Congrats from './Congrats';
import languageContext from './contexts/languageContext';
import successContext from './contexts/successContext';
/**
* Factory function to create a ReactWrapper for the Congrats component.
* @function setup
* @param {object} testValues - contextValues specific to this setup.
* @returns {ReactWrapper}
*/
const setup = ({ success, language }) => {
language = language || 'en';
success = success || false;
return mount(
<languageContext.Provider value={language}>
<successContext.SuccessProvider value={[success, jest.fn()]}>
<Congrats />
</successContext.SuccessProvider>
</languageContext.Provider>
);
}
describe('language picker', () => {
test('correctly renders congrats string in English by default', () => {
const wrapper = setup({ success: true });
expect(wrapper.text()).toBe('Congratulations! You guessed the word!');
});
test('correctly renders congrats string in emoji', () => {
const wrapper = setup({ success: true, language: "emoji" });
expect(wrapper.text()).toBe('🎯🎉');
});
});
test('renders without error', () => {
const wrapper = setup({});
const component = findByTestAttr(wrapper, 'component-congrats');
expect(component.length).toBe(1);
});
test('renders no text when `success` is false', () => {
const wrapper = setup({ success: false });
const component = findByTestAttr(wrapper, 'component-congrats');
expect(component.text()).toBe('');
});
test('renders non-empty congrats message when `success` is true', () => {
const wrapper = setup({ success: true });
const message = findByTestAttr(wrapper, 'congrats-message');
expect(message.text().length).not.toBe(0);
});
================================================
FILE: SOLUTIONS for Jotto Context Challenges/src/EnterSecretWordButton.js
================================================
// Challenge #4: Enter Secret Word
import React from "react";
import PropTypes from "prop-types";
import stringsModule from "./helpers/strings";
import languageContext from "./contexts/languageContext";
import guessedWordsContext from "./contexts/guessedWordsContext";
/**
* Functional react component for reset button.
* @function
* @param {object} props - React props.
* @returns {JSX.Element} - Rendered component (or null if `success` context is false).
*/
export default function EnterSecretWordButton({ setEnterSecretWord }) {
const language = React.useContext(languageContext);
const [ guessedWords ] = guessedWordsContext.useGuessedWords();
if (guessedWords.length > 0) {
return(<div data-test="component-secret-word-entry"></div>)
}
return (
<button
data-test="component-enter-secret-word-button"
className="btn btn-primary mb-2"
onClick={() => setEnterSecretWord(true)}
>
{stringsModule.getStringByLanguage(language, "enterSecretWord")}
</button>
)
}
EnterSecretWordButton.propTypes = {
setEnterSecretWord: PropTypes.func.isRequired,
}
// END: Challenge #4: Enter Secret Word
================================================
FILE: SOLUTIONS for Jotto Context Challenges/src/EnterSecretWordButton.test.js
================================================
// Challenge #3: Give Up
import React from 'react';
import { mount } from 'enzyme';
import { findByTestAttr, checkProps } from '../test/testUtils';
import EnterSecretWordButton from './EnterSecretWordButton';
import languageContext from './contexts/languageContext';
import guessedWordsContext from './contexts/guessedWordsContext';
// for testing that setEnterSecretWord is called w
gitextract_pv9iq0jq/
├── .gitignore
├── COPYING
├── LEGACY-class-based-redux-components/
│ ├── README
│ ├── SOLUTIONS for Jotto Redux Challenges/
│ │ ├── .gitignore
│ │ ├── README.md
│ │ ├── package.json
│ │ ├── public/
│ │ │ ├── index.html
│ │ │ └── manifest.json
│ │ ├── src/
│ │ │ ├── App.css
│ │ │ ├── App.js
│ │ │ ├── App.test.js
│ │ │ ├── Congrats.js
│ │ │ ├── Congrats.test.js
│ │ │ ├── EnterWordButton.js
│ │ │ ├── EnterWordButton.test.js
│ │ │ ├── EnterWordForm.js
│ │ │ ├── EnterWordForm.test.js
│ │ │ ├── GuessedWords.js
│ │ │ ├── GuessedWords.test.js
│ │ │ ├── Input.js
│ │ │ ├── Input.test.js
│ │ │ ├── NewWordButton.js
│ │ │ ├── NewWordButton.test.js
│ │ │ ├── SecretWordReveal.js
│ │ │ ├── SecretWordReveal.test.js
│ │ │ ├── ServerError.js
│ │ │ ├── ServerError.test.js
│ │ │ ├── TotalGuesses.js
│ │ │ ├── TotalGuesses.test.js
│ │ │ ├── actions/
│ │ │ │ ├── index.js
│ │ │ │ └── index.test.js
│ │ │ ├── configureStore.js
│ │ │ ├── helpers/
│ │ │ │ ├── index.js
│ │ │ │ └── index.test.js
│ │ │ ├── index.css
│ │ │ ├── index.js
│ │ │ ├── integration.test.js
│ │ │ ├── reducers/
│ │ │ │ ├── gaveUpReducer.js
│ │ │ │ ├── gaveUpReducer.test.js
│ │ │ │ ├── guessedWordsReducer.js
│ │ │ │ ├── guessedWordsReducer.test.js
│ │ │ │ ├── index.js
│ │ │ │ ├── secretWordReducer.js
│ │ │ │ ├── serverErrorReducer.js
│ │ │ │ ├── serverErrorReducer.test.js
│ │ │ │ ├── successReducer.js
│ │ │ │ ├── successReducer.test.js
│ │ │ │ ├── userEnterReducer.js
│ │ │ │ └── userEnterReducer.test.js
│ │ │ ├── registerServiceWorker.js
│ │ │ └── setupTests.js
│ │ └── test/
│ │ └── testUtils.js
│ └── jotto-redux-class-based/
│ ├── .gitignore
│ ├── README.md
│ ├── package.json
│ ├── public/
│ │ ├── index.html
│ │ └── manifest.json
│ ├── src/
│ │ ├── App.css
│ │ ├── App.js
│ │ ├── App.test.js
│ │ ├── Congrats.js
│ │ ├── Congrats.test.js
│ │ ├── GuessedWords.js
│ │ ├── GuessedWords.test.js
│ │ ├── Input.js
│ │ ├── Input.test.js
│ │ ├── actions/
│ │ │ ├── index.js
│ │ │ └── index.test.js
│ │ ├── configureStore.js
│ │ ├── helpers/
│ │ │ ├── index.js
│ │ │ └── index.test.js
│ │ ├── index.css
│ │ ├── index.js
│ │ ├── integration.test.js
│ │ ├── reducers/
│ │ │ ├── guessedWordsReducer.js
│ │ │ ├── index.js
│ │ │ ├── secretWordReducer.js
│ │ │ ├── successReducer.js
│ │ │ └── successReducer.test.js
│ │ ├── registerServiceWorker.js
│ │ └── setupTests.js
│ └── test/
│ └── testUtils.js
├── README.md
├── SOLUTIONS for Click Counter Challenges/
│ ├── .gitignore
│ ├── .npmrc
│ ├── README.md
│ ├── package.json
│ ├── public/
│ │ ├── index.html
│ │ ├── manifest.json
│ │ └── robots.txt
│ └── src/
│ ├── App.css
│ ├── App.js
│ ├── App.test.js
│ ├── index.css
│ ├── index.js
│ ├── registerServiceWorker.js
│ ├── serviceWorker.js
│ └── setupTests.js
├── SOLUTIONS for Jotto Context Challenges/
│ ├── .npmrc
│ ├── README.md
│ ├── package.json
│ ├── public/
│ │ ├── index.html
│ │ ├── manifest.json
│ │ └── robots.txt
│ ├── src/
│ │ ├── App.css
│ │ ├── App.js
│ │ ├── App.test.js
│ │ ├── Congrats.js
│ │ ├── Congrats.test.js
│ │ ├── EnterSecretWordButton.js
│ │ ├── EnterSecretWordButton.test.js
│ │ ├── GiveUpButton.js
│ │ ├── GiveUpButton.test.js
│ │ ├── GuessedWords.js
│ │ ├── GuessedWords.test.js
│ │ ├── Input.js
│ │ ├── Input.test.js
│ │ ├── LanguagePicker.js
│ │ ├── LanguagePicker.test.js
│ │ ├── NewWordButton.js
│ │ ├── NewWordButton.test.js
│ │ ├── SecretWordEntry.js
│ │ ├── SecretWordEntry.test.js
│ │ ├── SecretWordReveal.js
│ │ ├── SecretWordReveal.test.js
│ │ ├── ServerError.js
│ │ ├── ServerError.test.js
│ │ ├── actions/
│ │ │ ├── hookActions.js
│ │ │ └── hookActions.test.js
│ │ ├── contexts/
│ │ │ ├── guessedWordsContext.js
│ │ │ ├── guessedWordsContext.test.js
│ │ │ ├── languageContext.js
│ │ │ ├── successContext.js
│ │ │ └── successContext.test.js
│ │ ├── helpers/
│ │ │ ├── index.js
│ │ │ ├── index.test.js
│ │ │ ├── strings.js
│ │ │ └── strings.test.js
│ │ ├── index.css
│ │ ├── index.js
│ │ ├── integration_tests/
│ │ │ ├── enter_secret_word.test.js
│ │ │ ├── giveup.test.js
│ │ │ ├── guesses.test.js
│ │ │ └── resetgame.test.js
│ │ ├── serviceWorker.js
│ │ └── setupTests.js
│ └── test/
│ └── testUtils.js
├── SOLUTIONS for Jotto Redux Hooks Challenges/
│ ├── .gitignore
│ ├── .npmrc
│ ├── README.md
│ ├── package.json
│ ├── public/
│ │ ├── index.html
│ │ ├── manifest.json
│ │ └── robots.txt
│ ├── src/
│ │ ├── App.css
│ │ ├── App.js
│ │ ├── App.test.js
│ │ ├── Congrats.js
│ │ ├── Congrats.test.js
│ │ ├── EnterWordButton.js
│ │ ├── EnterWordButton.test.js
│ │ ├── EnterWordForm.js
│ │ ├── EnterWordForm.test.js
│ │ ├── GuessedWords.js
│ │ ├── GuessedWords.test.js
│ │ ├── Input.js
│ │ ├── Input.test.js
│ │ ├── NewWordButton.js
│ │ ├── NewWordButton.test.js
│ │ ├── SecretWordReveal.js
│ │ ├── SecretWordReveal.test.js
│ │ ├── ServerError.js
│ │ ├── ServerError.test.js
│ │ ├── TotalGuesses.js
│ │ ├── TotalGuesses.test.js
│ │ ├── actions/
│ │ │ ├── __mocks__/
│ │ │ │ └── index.js
│ │ │ ├── index.js
│ │ │ └── index.test.js
│ │ ├── config.js.template
│ │ ├── configureStore.js
│ │ ├── guessWord.test.js
│ │ ├── helpers/
│ │ │ ├── index.js
│ │ │ └── index.test.js
│ │ ├── index.css
│ │ ├── index.js
│ │ ├── integration.test.js
│ │ ├── reducers/
│ │ │ ├── gaveUpReducer.js
│ │ │ ├── gaveUpReducer.test.js
│ │ │ ├── guessedWordsReducer.js
│ │ │ ├── index.js
│ │ │ ├── secretWordReducer.js
│ │ │ ├── serverErrorReducer.js
│ │ │ ├── serverErrorReducer.test.js
│ │ │ ├── successReducer.js
│ │ │ ├── successReducer.test.js
│ │ │ ├── userEnterReducer.js
│ │ │ └── userEnterReducer.test.js
│ │ ├── reportWebVitals.js
│ │ └── setupTests.js
│ └── test/
│ └── testUtils.js
├── click-counter/
│ ├── .gitignore
│ ├── .npmrc
│ ├── README.md
│ ├── package.json
│ ├── public/
│ │ ├── index.html
│ │ └── manifest.json
│ └── src/
│ ├── App.css
│ ├── App.js
│ ├── App.test.js
│ ├── index.css
│ ├── index.js
│ ├── registerServiceWorker.js
│ ├── serviceWorker.js
│ └── setupTests.js
├── context-base/
│ ├── .gitignore
│ ├── .npmrc
│ ├── README.md
│ ├── package.json
│ ├── public/
│ │ ├── index.html
│ │ ├── manifest.json
│ │ └── robots.txt
│ ├── src/
│ │ ├── App.css
│ │ ├── App.js
│ │ ├── App.test.js
│ │ ├── Congrats.js
│ │ ├── Congrats.test.js
│ │ ├── GuessedWords.js
│ │ ├── GuessedWords.test.js
│ │ ├── Input.js
│ │ ├── Input.test.js
│ │ ├── actions/
│ │ │ ├── __mocks__/
│ │ │ │ └── index.js
│ │ │ ├── index.js
│ │ │ └── index.test.js
│ │ ├── guessWord.test.js
│ │ ├── helpers/
│ │ │ ├── index.js
│ │ │ └── index.test.js
│ │ ├── index.css
│ │ ├── index.js
│ │ ├── reportWebVitals.js
│ │ └── setupTests.js
│ └── test/
│ └── testUtils.js
├── jotto-context/
│ ├── .gitignore
│ ├── .npmrc
│ ├── README.md
│ ├── package.json
│ ├── public/
│ │ ├── index.html
│ │ ├── manifest.json
│ │ └── robots.txt
│ ├── src/
│ │ ├── App.css
│ │ ├── App.js
│ │ ├── App.test.js
│ │ ├── Congrats.js
│ │ ├── Congrats.test.js
│ │ ├── GuessedWords.js
│ │ ├── GuessedWords.test.js
│ │ ├── Input.js
│ │ ├── Input.test.js
│ │ ├── LanguagePicker.js
│ │ ├── LanguagePicker.test.js
│ │ ├── actions/
│ │ │ ├── __mocks__/
│ │ │ │ └── index.js
│ │ │ ├── index.js
│ │ │ └── index.test.js
│ │ ├── contexts/
│ │ │ ├── guessedWordsContext.js
│ │ │ ├── guessedWordsContext.test.js
│ │ │ ├── languageContext.js
│ │ │ ├── successContext.js
│ │ │ └── successContext.test.js
│ │ ├── guessWord.test.js
│ │ ├── helpers/
│ │ │ ├── index.js
│ │ │ ├── index.test.js
│ │ │ ├── strings.js
│ │ │ └── strings.test.js
│ │ ├── index.css
│ │ ├── index.js
│ │ ├── reportWebVitals.js
│ │ └── setupTests.js
│ └── test/
│ └── testUtils.js
├── jotto-redux-hooks/
│ ├── .gitignore
│ ├── .npmrc
│ ├── README.md
│ ├── package.json
│ ├── public/
│ │ ├── index.html
│ │ ├── manifest.json
│ │ └── robots.txt
│ ├── src/
│ │ ├── App.css
│ │ ├── App.js
│ │ ├── App.test.js
│ │ ├── Congrats.js
│ │ ├── Congrats.test.js
│ │ ├── GuessedWords.js
│ │ ├── GuessedWords.test.js
│ │ ├── Input.js
│ │ ├── Input.test.js
│ │ ├── actions/
│ │ │ ├── __mocks__/
│ │ │ │ └── index.js
│ │ │ ├── index.js
│ │ │ └── index.test.js
│ │ ├── configureStore.js
│ │ ├── guessWord.test.js
│ │ ├── helpers/
│ │ │ ├── index.js
│ │ │ └── index.test.js
│ │ ├── index.css
│ │ ├── index.js
│ │ ├── integration.test.js
│ │ ├── reducers/
│ │ │ ├── guessedWordsReducer.js
│ │ │ ├── index.js
│ │ │ ├── secretWordReducer.js
│ │ │ ├── successReducer.js
│ │ │ └── successReducer.test.js
│ │ ├── reportWebVitals.js
│ │ └── setupTests.js
│ └── test/
│ └── testUtils.js
└── random-word-server/
├── .gitignore
├── .npmrc
├── README.md
├── five-letter-words.json
├── package.json
├── server.js
└── server.test.js
SYMBOL INDEX (103 symbols across 57 files)
FILE: LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/App.js
class UnconnectedApp (line 40) | class UnconnectedApp extends Component {
method componentDidMount (line 45) | componentDidMount() {
method render (line 50) | render() {
FILE: LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/EnterWordForm.js
class EnterWordForm (line 5) | class EnterWordForm extends React.Component {
method constructor (line 6) | constructor(props) {
method submitForm (line 11) | submitForm(evt) {
method render (line 18) | render() {
FILE: LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/EnterWordForm.test.js
method preventDefault (line 65) | preventDefault() {}
FILE: LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/Input.js
class UnconnectedInput (line 8) | class UnconnectedInput extends Component {
method constructor (line 14) | constructor(props) {
method submitGuessedWord (line 27) | submitGuessedWord(evt) {
method giveUpOnClick (line 38) | giveUpOnClick(evt) {
method render (line 43) | render() {
FILE: LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/Input.test.js
method preventDefault (line 90) | preventDefault() {}
method preventDefault (line 113) | preventDefault() {}
FILE: LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/actions/index.js
constant WORDNIK_URL (line 6) | const WORDNIK_URL = `https://api.wordnik.com/v4/words.json/randomWord?ha...
FILE: LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/helpers/index.js
function getLetterMatchCount (line 7) | function getLetterMatchCount(guessedWord, secretWord) {
FILE: LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/registerServiceWorker.js
function register (line 21) | function register() {
function registerValidSW (line 55) | function registerValidSW(swUrl) {
function checkValidServiceWorker (line 84) | function checkValidServiceWorker(swUrl) {
function unregister (line 111) | function unregister() {
FILE: LEGACY-class-based-redux-components/jotto-redux-class-based/src/App.js
class UnconnectedApp (line 10) | class UnconnectedApp extends Component {
method componentDidMount (line 15) | componentDidMount() {
method render (line 20) | render() {
FILE: LEGACY-class-based-redux-components/jotto-redux-class-based/src/Input.js
class UnconnectedInput (line 6) | class UnconnectedInput extends Component {
method constructor (line 12) | constructor(props) {
method submitGuessedWord (line 21) | submitGuessedWord(evt) {
method render (line 30) | render() {
FILE: LEGACY-class-based-redux-components/jotto-redux-class-based/src/Input.test.js
method preventDefault (line 90) | preventDefault() {}
FILE: LEGACY-class-based-redux-components/jotto-redux-class-based/src/helpers/index.js
function getLetterMatchCount (line 7) | function getLetterMatchCount(guessedWord, secretWord) {
FILE: LEGACY-class-based-redux-components/jotto-redux-class-based/src/registerServiceWorker.js
function register (line 21) | function register() {
function registerValidSW (line 55) | function registerValidSW(swUrl) {
function checkValidServiceWorker (line 84) | function checkValidServiceWorker(swUrl) {
function unregister (line 111) | function unregister() {
FILE: SOLUTIONS for Click Counter Challenges/src/App.js
function App (line 5) | function App() {
FILE: SOLUTIONS for Click Counter Challenges/src/registerServiceWorker.js
function register (line 21) | function register() {
function registerValidSW (line 55) | function registerValidSW(swUrl) {
function checkValidServiceWorker (line 84) | function checkValidServiceWorker(swUrl) {
function unregister (line 111) | function unregister() {
FILE: SOLUTIONS for Click Counter Challenges/src/serviceWorker.js
function register (line 23) | function register(config) {
function registerValidSW (line 57) | function registerValidSW(swUrl, config) {
function checkValidServiceWorker (line 101) | function checkValidServiceWorker(swUrl, config) {
function unregister (line 131) | function unregister() {
FILE: SOLUTIONS for Jotto Context Challenges/src/App.js
function reducer (line 25) | function reducer(state, action) {
function App (line 49) | function App() {
FILE: SOLUTIONS for Jotto Context Challenges/src/EnterSecretWordButton.js
function EnterSecretWordButton (line 15) | function EnterSecretWordButton({ setEnterSecretWord }) {
FILE: SOLUTIONS for Jotto Context Challenges/src/GiveUpButton.js
function GiveUpButton (line 15) | function GiveUpButton({ setGivenUp }) {
FILE: SOLUTIONS for Jotto Context Challenges/src/Input.js
function Input (line 10) | function Input({ secretWord }) {
FILE: SOLUTIONS for Jotto Context Challenges/src/Input.test.js
method preventDefault (line 61) | preventDefault() {}
FILE: SOLUTIONS for Jotto Context Challenges/src/LanguagePicker.js
function LanguagePicker (line 4) | function LanguagePicker({ setLanguage }) {
FILE: SOLUTIONS for Jotto Context Challenges/src/NewWordButton.js
function NewWordButton (line 18) | function NewWordButton(props) {
FILE: SOLUTIONS for Jotto Context Challenges/src/SecretWordEntry.js
function SecretWordEntry (line 14) | function SecretWordEntry({ setEnterSecretWord, setSecretWord }) {
FILE: SOLUTIONS for Jotto Context Challenges/src/SecretWordReveal.js
function SecretWordReveal (line 15) | function SecretWordReveal({ secretWord }) {
FILE: SOLUTIONS for Jotto Context Challenges/src/ServerError.js
function ServerError (line 14) | function ServerError(props) {
FILE: SOLUTIONS for Jotto Context Challenges/src/contexts/guessedWordsContext.js
function useGuessedWords (line 11) | function useGuessedWords() {
function GuessedWordsProvider (line 32) | function GuessedWordsProvider(props) {
FILE: SOLUTIONS for Jotto Context Challenges/src/contexts/successContext.js
function useSuccess (line 11) | function useSuccess() {
function SuccessProvider (line 26) | function SuccessProvider(props) {
FILE: SOLUTIONS for Jotto Context Challenges/src/helpers/index.js
function getLetterMatchCount (line 7) | function getLetterMatchCount(guessedWord, secretWord) {
FILE: SOLUTIONS for Jotto Context Challenges/src/helpers/strings.js
function getStringByLanguage (line 58) | function getStringByLanguage(languageCode, stringKey, strings=languageSt...
FILE: SOLUTIONS for Jotto Context Challenges/src/integration_tests/guesses.test.js
function setup (line 10) | function setup(guessedWordsStrings=[], secretWord="party") {
FILE: SOLUTIONS for Jotto Context Challenges/src/serviceWorker.js
function register (line 23) | function register(config) {
function registerValidSW (line 57) | function registerValidSW(swUrl, config) {
function checkValidServiceWorker (line 101) | function checkValidServiceWorker(swUrl, config) {
function unregister (line 129) | function unregister() {
FILE: SOLUTIONS for Jotto Redux Hooks Challenges/src/App.js
function App (line 42) | function App() {
FILE: SOLUTIONS for Jotto Redux Hooks Challenges/src/EnterWordForm.test.js
method preventDefault (line 67) | preventDefault() {}
FILE: SOLUTIONS for Jotto Redux Hooks Challenges/src/Input.js
function Input (line 8) | function Input({ secretWord }) {
FILE: SOLUTIONS for Jotto Redux Hooks Challenges/src/actions/index.js
constant WORDNIK_URL (line 6) | const WORDNIK_URL = `https://api.wordnik.com/v4/words.json/randomWord?ha...
FILE: SOLUTIONS for Jotto Redux Hooks Challenges/src/guessWord.test.js
method preventDefault (line 29) | preventDefault() {}
method preventDefault (line 80) | preventDefault() {}
FILE: SOLUTIONS for Jotto Redux Hooks Challenges/src/helpers/index.js
function getLetterMatchCount (line 7) | function getLetterMatchCount(guessedWord, secretWord) {
FILE: click-counter/src/App.js
function App (line 5) | function App() {
FILE: click-counter/src/registerServiceWorker.js
function register (line 21) | function register() {
function registerValidSW (line 55) | function registerValidSW(swUrl) {
function checkValidServiceWorker (line 84) | function checkValidServiceWorker(swUrl) {
function unregister (line 111) | function unregister() {
FILE: click-counter/src/serviceWorker.js
function register (line 23) | function register(config) {
function registerValidSW (line 57) | function registerValidSW(swUrl, config) {
function checkValidServiceWorker (line 101) | function checkValidServiceWorker(swUrl, config) {
function unregister (line 131) | function unregister() {
FILE: context-base/src/App.js
function App (line 9) | function App() {
FILE: context-base/src/Input.js
function Input (line 4) | function Input({ secretWord, success }) {
FILE: context-base/src/guessWord.test.js
method preventDefault (line 26) | preventDefault() {}
method preventDefault (line 77) | preventDefault() {}
FILE: context-base/src/helpers/index.js
function getLetterMatchCount (line 7) | function getLetterMatchCount(guessedWord, secretWord) {
FILE: jotto-context/src/App.js
function App (line 34) | function App() {
FILE: jotto-context/src/Input.js
function Input (line 10) | function Input({ secretWord }) {
FILE: jotto-context/src/LanguagePicker.js
function LanguagePicker (line 4) | function LanguagePicker({ setLanguage }) {
FILE: jotto-context/src/contexts/guessedWordsContext.js
function useGuessedWords (line 11) | function useGuessedWords() {
function GuessedWordsProvider (line 32) | function GuessedWordsProvider(props) {
FILE: jotto-context/src/contexts/successContext.js
function useSuccess (line 11) | function useSuccess() {
function SuccessProvider (line 26) | function SuccessProvider(props) {
FILE: jotto-context/src/guessWord.test.js
method preventDefault (line 40) | preventDefault() {}
method preventDefault (line 45) | preventDefault() {}
method preventDefault (line 97) | preventDefault() {}
FILE: jotto-context/src/helpers/index.js
function getLetterMatchCount (line 7) | function getLetterMatchCount(guessedWord, secretWord) {
FILE: jotto-context/src/helpers/strings.js
function getStringByLanguage (line 22) | function getStringByLanguage(languageCode, stringKey, strings=languageSt...
FILE: jotto-redux-hooks/src/App.js
function App (line 10) | function App() {
FILE: jotto-redux-hooks/src/Input.js
function Input (line 7) | function Input({ secretWord }) {
FILE: jotto-redux-hooks/src/guessWord.test.js
method preventDefault (line 29) | preventDefault() {}
method preventDefault (line 80) | preventDefault() {}
FILE: jotto-redux-hooks/src/helpers/index.js
function getLetterMatchCount (line 7) | function getLetterMatchCount(guessedWord, secretWord) {
Condensed preview — 318 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (477K chars).
[
{
"path": ".gitignore",
"chars": 31,
"preview": "node_modules\n.DS_Store\n.vscode\n"
},
{
"path": "COPYING",
"chars": 34520,
"preview": " GNU AFFERO GENERAL PUBLIC LICENSE\n Version 3, 19 November 2007\n\n Copyright (C)"
},
{
"path": "LEGACY-class-based-redux-components/README",
"chars": 114,
"preview": "This is legacy code from when the course used class-based\ncomponents for the Redux portion. It is NOT maintained!\n"
},
{
"path": "LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/.gitignore",
"chars": 295,
"preview": "# See https://help.github.com/ignore-files/ for more about ignoring files.\n\n# dependencies\n/node_modules\n\n# testing\n/cov"
},
{
"path": "LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/README.md",
"chars": 3769,
"preview": "# Jotto\n### A React / Redux app used to demonstrate testing\n\n## Solutions\n\nSolutions can be found in the [SOLUTIONS for "
},
{
"path": "LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/package.json",
"chars": 699,
"preview": "{\n \"name\": \"jotto\",\n \"version\": \"0.1.0\",\n \"private\": true,\n \"dependencies\": {\n \"axios\": \"^0.18.1\",\n \"prop-type"
},
{
"path": "LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/public/index.html",
"chars": 1806,
"preview": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-wid"
},
{
"path": "LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/public/manifest.json",
"chars": 317,
"preview": "{\n \"short_name\": \"React App\",\n \"name\": \"Create React App Sample\",\n \"icons\": [\n {\n \"src\": \"favicon.ico\",\n "
},
{
"path": "LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/App.css",
"chars": 41,
"preview": ".spacer-bottom {\n margin-bottom: 20px;\n}"
},
{
"path": "LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/App.js",
"chars": 3249,
"preview": "import React, { Component } from 'react';\nimport { connect } from 'react-redux';\nimport './App.css';\n\n// Challenge #1: N"
},
{
"path": "LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/App.test.js",
"chars": 2870,
"preview": "import React from 'react';\nimport { shallow } from 'enzyme';\n\nimport { storeFactory } from '../test/testUtils';\nimport A"
},
{
"path": "LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/Congrats.js",
"chars": 712,
"preview": "import React from 'react';\nimport PropTypes from 'prop-types';\n\n/**\n * Functional react component for congratulatory mes"
},
{
"path": "LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/Congrats.test.js",
"chars": 1296,
"preview": "import React from 'react';\nimport { shallow } from 'enzyme';\n\nimport { findByTestAttr, checkProps } from '../test/testUt"
},
{
"path": "LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/EnterWordButton.js",
"chars": 652,
"preview": "// Challenge #4: Enter Secret Word\nimport React from 'react';\nimport PropTypes from 'prop-types';\n\nconst EnterWordButton"
},
{
"path": "LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/EnterWordButton.test.js",
"chars": 2055,
"preview": "// Challenge #4: Enter Secret Word\nimport React from 'react';\nimport { shallow } from 'enzyme';\n\nimport { findByTestAttr"
},
{
"path": "LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/EnterWordForm.js",
"chars": 1319,
"preview": "// Challenge #4: Enter Secret Word\nimport React from 'react';\nimport PropTypes from 'prop-types';\n\nexport class EnterWor"
},
{
"path": "LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/EnterWordForm.test.js",
"chars": 2677,
"preview": "// Challenge #4: Enter Secret Word\nimport React from 'react';\nimport { shallow } from 'enzyme';\n\nimport { findByTestAttr"
},
{
"path": "LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/GuessedWords.js",
"chars": 1545,
"preview": "import React from 'react';\nimport PropTypes from 'prop-types';\n\nconst GuessedWords = (props) => {\n let contents\n if (p"
},
{
"path": "LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/GuessedWords.test.js",
"chars": 2459,
"preview": "import React from 'react';\nimport { shallow } from 'enzyme';\nimport { findByTestAttr, checkProps } from '../test/testUti"
},
{
"path": "LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/Input.js",
"chars": 2290,
"preview": "import React, { Component } from 'react';\nimport { connect } from 'react-redux';\n\n// Challenge #3: Give Up Button\nimport"
},
{
"path": "LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/Input.test.js",
"chars": 4257,
"preview": "import React from 'react';\nimport { shallow } from 'enzyme';\n\nimport { findByTestAttr, storeFactory } from '../test/test"
},
{
"path": "LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/NewWordButton.js",
"chars": 803,
"preview": "// Challenge #2: Reset Game\n\nimport React from 'react';\nimport PropTypes from 'prop-types';\n\n/**\n * Functional react com"
},
{
"path": "LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/NewWordButton.test.js",
"chars": 2034,
"preview": "// Challenge #2: Reset Game\n\nimport React from 'react';\nimport { shallow } from 'enzyme';\n\nimport { findByTestAttr, chec"
},
{
"path": "LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/SecretWordReveal.js",
"chars": 965,
"preview": "// Challenge #3: Give Up Button\nimport React from 'react';\nimport PropTypes from 'prop-types';\n\n/**\n * Functional react "
},
{
"path": "LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/SecretWordReveal.test.js",
"chars": 1484,
"preview": "// Challenge #3: Give Up Button\n\nimport React from 'react';\nimport { shallow } from 'enzyme';\n\nimport { findByTestAttr, "
},
{
"path": "LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/ServerError.js",
"chars": 301,
"preview": "// Challenge #5: Server Error\nimport React from 'react';\n\nexport default (props) => {\n return (\n <div data-test=\"com"
},
{
"path": "LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/ServerError.test.js",
"chars": 674,
"preview": "// Challenge #5: Server Error\nimport React from 'react';\nimport { shallow } from 'enzyme';\n\nimport { findByTestAttr } fr"
},
{
"path": "LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/TotalGuesses.js",
"chars": 560,
"preview": "// Challenge #1: Number of Guesses\n\nimport React from 'react';\nimport PropTypes from 'prop-types';\n\n/**\n * Functional re"
},
{
"path": "LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/TotalGuesses.test.js",
"chars": 1046,
"preview": "// Challenge #1: Number of Guesses\n\nimport React from 'react';\nimport { shallow } from 'enzyme';\n\nimport { findByTestAtt"
},
{
"path": "LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/actions/index.js",
"chars": 4530,
"preview": "import axios from 'axios';\n\nimport { getLetterMatchCount } from '../helpers';\nimport { wordnikKey } from '../config.js';"
},
{
"path": "LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/actions/index.test.js",
"chars": 2007,
"preview": "import moxios from 'moxios';\n\nimport { storeFactory } from '../../test/testUtils';\nimport { getSecretWord } from './';\n\n"
},
{
"path": "LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/configureStore.js",
"chars": 308,
"preview": "import { createStore, applyMiddleware } from 'redux';\nimport ReduxThunk from 'redux-thunk';\nimport rootReducer from './r"
},
{
"path": "LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/helpers/index.js",
"chars": 489,
"preview": "/**\n * @method getLetterMatchCount\n * @param {string} guessedWord - Guessed word.\n * @param {string} secretWord - Secret"
},
{
"path": "LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/helpers/index.test.js",
"chars": 702,
"preview": "import { getLetterMatchCount } from './';\n\ndescribe('getLetterMatchCount', () => {\n const secretWord = 'party';\n test("
},
{
"path": "LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/index.css",
"chars": 63,
"preview": "body {\n margin: 0;\n padding: 0;\n font-family: sans-serif;\n}\n"
},
{
"path": "LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/index.js",
"chars": 382,
"preview": "import React from 'react';\nimport ReactDOM from 'react-dom';\nimport { Provider } from 'react-redux';\n\nimport './index.cs"
},
{
"path": "LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/integration.test.js",
"chars": 4097,
"preview": "import { storeFactory } from '../test/testUtils';\nimport { guessWord } from './actions';\nimport { setUserSecretWord } fr"
},
{
"path": "LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/reducers/gaveUpReducer.js",
"chars": 1165,
"preview": "// Challenge #3: Give Up Button\n\n/* NOTE: This is not the optimal way to track whether or not the user has given up. \n W"
},
{
"path": "LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/reducers/gaveUpReducer.test.js",
"chars": 770,
"preview": "// Challenge #3: Give Up Button\nimport { actionTypes } from '../actions';\nimport gaveUpReducer from './gaveUpReducer';\n\n"
},
{
"path": "LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/reducers/guessedWordsReducer.js",
"chars": 528,
"preview": "import { actionTypes } from '../actions';\n\n/**\n * @function guessedWordsReducer\n * @param {array} state - Array of guess"
},
{
"path": "LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/reducers/guessedWordsReducer.test.js",
"chars": 560,
"preview": "// Challenge #2: Reset Game\nimport { actionTypes } from '../actions';\nimport guessedWordsReducer from './guessedWordsRed"
},
{
"path": "LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/reducers/index.js",
"chars": 781,
"preview": "import { combineReducers } from 'redux';\nimport success from './successReducer';\nimport guessedWords from './guessedWord"
},
{
"path": "LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/reducers/secretWordReducer.js",
"chars": 423,
"preview": "import { actionTypes } from '../actions';\n\n/**\n * @function secretWordReducer\n * @param {string} state - State before re"
},
{
"path": "LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/reducers/serverErrorReducer.js",
"chars": 470,
"preview": "// Challenge #5: Server Error\nimport { actionTypes } from '../actions';\n\n/**\n * @function serverErrorReducer\n * @param {"
},
{
"path": "LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/reducers/serverErrorReducer.test.js",
"chars": 543,
"preview": "// Challenge #5: Server Error\nimport { actionTypes } from '../actions';\nimport serverErrorReducer from './serverErrorRed"
},
{
"path": "LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/reducers/successReducer.js",
"chars": 526,
"preview": "import { actionTypes } from '../actions';\n\n/**\n * @function successReducer\n * @param {boolean} state - Whether the user "
},
{
"path": "LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/reducers/successReducer.test.js",
"chars": 785,
"preview": "import { actionTypes } from '../actions';\nimport successReducer from './successReducer';\n\ntest('returns default initial "
},
{
"path": "LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/reducers/userEnterReducer.js",
"chars": 594,
"preview": "// Challenge #4: Enter Secret Word\nimport { actionTypes } from '../actions';\n\n/**\n * @function userEnterReducer\n * @para"
},
{
"path": "LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/reducers/userEnterReducer.test.js",
"chars": 1084,
"preview": "// Challenge #4: Enter Secret Word\nimport { actionTypes } from '../actions';\nimport userEnterReducer from './userEnterRe"
},
{
"path": "LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/registerServiceWorker.js",
"chars": 4384,
"preview": "// In production, we register a service worker to serve assets from local cache.\n\n// This lets the app load faster on su"
},
{
"path": "LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/src/setupTests.js",
"chars": 184,
"preview": "import Enzyme, { shallow } from 'enzyme';\nimport EnzymeAdapter from 'enzyme-adapter-react-16';\n\nEnzyme.configure({\n ada"
},
{
"path": "LEGACY-class-based-redux-components/SOLUTIONS for Jotto Redux Challenges/test/testUtils.js",
"chars": 1174,
"preview": "import checkPropTypes from 'check-prop-types';\nimport { createStore, applyMiddleware } from 'redux';\n\nimport rootReducer"
},
{
"path": "LEGACY-class-based-redux-components/jotto-redux-class-based/.gitignore",
"chars": 310,
"preview": "# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.\n\n# dependencies\n/node_modules\n/.pn"
},
{
"path": "LEGACY-class-based-redux-components/jotto-redux-class-based/README.md",
"chars": 4107,
"preview": "# Jotto\n### A React / Redux app used to demonstrate testing\n\n## Branches\n\n* `master`\n\n This branch represents the proj"
},
{
"path": "LEGACY-class-based-redux-components/jotto-redux-class-based/package.json",
"chars": 899,
"preview": "{\n \"name\": \"jotto\",\n \"version\": \"0.1.0\",\n \"private\": true,\n \"dependencies\": {\n \"axios\": \"^0.19.0\",\n \"check-pro"
},
{
"path": "LEGACY-class-based-redux-components/jotto-redux-class-based/public/index.html",
"chars": 1806,
"preview": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-wid"
},
{
"path": "LEGACY-class-based-redux-components/jotto-redux-class-based/public/manifest.json",
"chars": 317,
"preview": "{\n \"short_name\": \"React App\",\n \"name\": \"Create React App Sample\",\n \"icons\": [\n {\n \"src\": \"favicon.ico\",\n "
},
{
"path": "LEGACY-class-based-redux-components/jotto-redux-class-based/src/App.css",
"chars": 0,
"preview": ""
},
{
"path": "LEGACY-class-based-redux-components/jotto-redux-class-based/src/App.js",
"chars": 919,
"preview": "import React, { Component } from 'react';\nimport { connect } from 'react-redux';\nimport './App.css';\n\nimport GuessedWord"
},
{
"path": "LEGACY-class-based-redux-components/jotto-redux-class-based/src/App.test.js",
"chars": 1994,
"preview": "import React from 'react';\nimport { shallow } from 'enzyme';\n\nimport { storeFactory } from '../test/testUtils';\nimport A"
},
{
"path": "LEGACY-class-based-redux-components/jotto-redux-class-based/src/Congrats.js",
"chars": 712,
"preview": "import React from 'react';\nimport PropTypes from 'prop-types';\n\n/**\n * Functional react component for congratulatory mes"
},
{
"path": "LEGACY-class-based-redux-components/jotto-redux-class-based/src/Congrats.test.js",
"chars": 1296,
"preview": "import React from 'react';\nimport { shallow } from 'enzyme';\n\nimport { findByTestAttr, checkProps } from '../test/testUt"
},
{
"path": "LEGACY-class-based-redux-components/jotto-redux-class-based/src/GuessedWords.js",
"chars": 1206,
"preview": "import React from 'react';\nimport PropTypes from 'prop-types';\n\nconst GuessedWords = (props) => {\n let contents\n if (p"
},
{
"path": "LEGACY-class-based-redux-components/jotto-redux-class-based/src/GuessedWords.test.js",
"chars": 2018,
"preview": "import React from 'react';\nimport { shallow } from 'enzyme';\nimport { findByTestAttr, checkProps } from '../test/testUti"
},
{
"path": "LEGACY-class-based-redux-components/jotto-redux-class-based/src/Input.js",
"chars": 1655,
"preview": "import React, { Component } from 'react';\nimport { connect } from 'react-redux';\n\nimport { guessWord } from './actions';"
},
{
"path": "LEGACY-class-based-redux-components/jotto-redux-class-based/src/Input.test.js",
"chars": 3379,
"preview": "import React from 'react';\nimport { shallow } from 'enzyme';\n\nimport { findByTestAttr, storeFactory } from '../test/test"
},
{
"path": "LEGACY-class-based-redux-components/jotto-redux-class-based/src/actions/index.js",
"chars": 1316,
"preview": "import axios from 'axios';\n\nimport { getLetterMatchCount } from '../helpers';\n\nexport const actionTypes = {\n CORRECT_GU"
},
{
"path": "LEGACY-class-based-redux-components/jotto-redux-class-based/src/actions/index.test.js",
"chars": 734,
"preview": "import moxios from 'moxios';\n\nimport { storeFactory } from '../../test/testUtils';\nimport { getSecretWord } from './';\n\n"
},
{
"path": "LEGACY-class-based-redux-components/jotto-redux-class-based/src/configureStore.js",
"chars": 308,
"preview": "import { createStore, applyMiddleware } from 'redux';\nimport ReduxThunk from 'redux-thunk';\nimport rootReducer from './r"
},
{
"path": "LEGACY-class-based-redux-components/jotto-redux-class-based/src/helpers/index.js",
"chars": 463,
"preview": "/**\n * @method getLetterMatchCount\n * @param {string} guessedWord - Guessed word.\n * @param {string} secretWord - Secret"
},
{
"path": "LEGACY-class-based-redux-components/jotto-redux-class-based/src/helpers/index.test.js",
"chars": 702,
"preview": "import { getLetterMatchCount } from './';\n\ndescribe('getLetterMatchCount', () => {\n const secretWord = 'party';\n test("
},
{
"path": "LEGACY-class-based-redux-components/jotto-redux-class-based/src/index.css",
"chars": 63,
"preview": "body {\n margin: 0;\n padding: 0;\n font-family: sans-serif;\n}\n"
},
{
"path": "LEGACY-class-based-redux-components/jotto-redux-class-based/src/index.js",
"chars": 382,
"preview": "import React from 'react';\nimport ReactDOM from 'react-dom';\nimport { Provider } from 'react-redux';\n\nimport './index.cs"
},
{
"path": "LEGACY-class-based-redux-components/jotto-redux-class-based/src/integration.test.js",
"chars": 2230,
"preview": "import { storeFactory } from '../test/testUtils';\nimport { guessWord } from './actions';\n\ndescribe('guessWord action dis"
},
{
"path": "LEGACY-class-based-redux-components/jotto-redux-class-based/src/reducers/guessedWordsReducer.js",
"chars": 407,
"preview": "import { actionTypes } from '../actions';\n\n/**\n * @function guessedWordsReducer\n * @param {array} state - Array of guess"
},
{
"path": "LEGACY-class-based-redux-components/jotto-redux-class-based/src/reducers/index.js",
"chars": 256,
"preview": "import { combineReducers } from 'redux';\nimport success from './successReducer';\nimport guessedWords from './guessedWord"
},
{
"path": "LEGACY-class-based-redux-components/jotto-redux-class-based/src/reducers/secretWordReducer.js",
"chars": 423,
"preview": "import { actionTypes } from '../actions';\n\n/**\n * @function secretWordReducer\n * @param {string} state - State before re"
},
{
"path": "LEGACY-class-based-redux-components/jotto-redux-class-based/src/reducers/successReducer.js",
"chars": 384,
"preview": "import { actionTypes } from '../actions';\n\n/**\n * @function successReducer\n * @param {array} state - Array of guessed wo"
},
{
"path": "LEGACY-class-based-redux-components/jotto-redux-class-based/src/reducers/successReducer.test.js",
"chars": 463,
"preview": "import { actionTypes } from '../actions';\nimport successReducer from './successReducer';\n\ntest('returns default initial "
},
{
"path": "LEGACY-class-based-redux-components/jotto-redux-class-based/src/registerServiceWorker.js",
"chars": 4384,
"preview": "// In production, we register a service worker to serve assets from local cache.\n\n// This lets the app load faster on su"
},
{
"path": "LEGACY-class-based-redux-components/jotto-redux-class-based/src/setupTests.js",
"chars": 184,
"preview": "import Enzyme, { shallow } from 'enzyme';\nimport EnzymeAdapter from 'enzyme-adapter-react-16';\n\nEnzyme.configure({\n ada"
},
{
"path": "LEGACY-class-based-redux-components/jotto-redux-class-based/test/testUtils.js",
"chars": 1174,
"preview": "import checkPropTypes from 'check-prop-types';\nimport { createStore, applyMiddleware } from 'redux';\n\nimport rootReducer"
},
{
"path": "README.md",
"chars": 188,
"preview": "# udemy-ENZYME\n\nCode for projects presented in Udemy [React Testing with Jest and Enzyme](https://www.udemy.com/course/r"
},
{
"path": "SOLUTIONS for Click Counter Challenges/.gitignore",
"chars": 285,
"preview": "# See https://help.github.com/ignore-files/ for more about ignoring files.\n\n# dependencies\n/node_modules\n\n# testing\n/cov"
},
{
"path": "SOLUTIONS for Click Counter Challenges/.npmrc",
"chars": 38,
"preview": "fund=false\naudit=false\nloglevel=error\n"
},
{
"path": "SOLUTIONS for Click Counter Challenges/README.md",
"chars": 2877,
"preview": "This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).\n\n## Available Scrip"
},
{
"path": "SOLUTIONS for Click Counter Challenges/package.json",
"chars": 856,
"preview": "{\n \"name\": \"click-counter-functional\",\n \"version\": \"0.1.0\",\n \"private\": true,\n \"dependencies\": {\n \"@testing-libra"
},
{
"path": "SOLUTIONS for Click Counter Challenges/public/index.html",
"chars": 1721,
"preview": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\" />\n <link rel=\"icon\" href=\"%PUBLIC_URL%/favicon.i"
},
{
"path": "SOLUTIONS for Click Counter Challenges/public/manifest.json",
"chars": 492,
"preview": "{\n \"short_name\": \"React App\",\n \"name\": \"Create React App Sample\",\n \"icons\": [\n {\n \"src\": \"favicon.ico\",\n "
},
{
"path": "SOLUTIONS for Click Counter Challenges/public/robots.txt",
"chars": 67,
"preview": "# https://www.robotstxt.org/robotstxt.html\nUser-agent: *\nDisallow:\n"
},
{
"path": "SOLUTIONS for Click Counter Challenges/src/App.css",
"chars": 734,
"preview": ".App {\n text-align: center;\n}\n\n.App-logo {\n height: 40vmin;\n pointer-events: none;\n}\n\n@media (prefers-reduced-motion:"
},
{
"path": "SOLUTIONS for Click Counter Challenges/src/App.js",
"chars": 1216,
"preview": "import React from 'react';\nimport logo from './logo.svg';\nimport './App.css';\n\nfunction App() {\n const [count, setCount"
},
{
"path": "SOLUTIONS for Click Counter Challenges/src/App.test.js",
"chars": 4651,
"preview": "import React from \"react\";\nimport Enzyme, { shallow } from \"enzyme\";\nimport EnzymeAdapter from \"enzyme-adapter-react-16\""
},
{
"path": "SOLUTIONS for Click Counter Challenges/src/index.css",
"chars": 366,
"preview": "body {\n margin: 0;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',\n 'Ubuntu', 'Can"
},
{
"path": "SOLUTIONS for Click Counter Challenges/src/index.js",
"chars": 503,
"preview": "import React from 'react';\nimport ReactDOM from 'react-dom';\nimport './index.css';\nimport App from './App';\nimport * as "
},
{
"path": "SOLUTIONS for Click Counter Challenges/src/registerServiceWorker.js",
"chars": 4384,
"preview": "// In production, we register a service worker to serve assets from local cache.\n\n// This lets the app load faster on su"
},
{
"path": "SOLUTIONS for Click Counter Challenges/src/serviceWorker.js",
"chars": 5086,
"preview": "// This optional code is used to register a service worker.\n// register() is not called by default.\n\n// This lets the ap"
},
{
"path": "SOLUTIONS for Click Counter Challenges/src/setupTests.js",
"chars": 255,
"preview": "// jest-dom adds custom jest matchers for asserting on DOM nodes.\n// allows you to do things like:\n// expect(element).to"
},
{
"path": "SOLUTIONS for Jotto Context Challenges/.npmrc",
"chars": 38,
"preview": "fund=false\naudit=false\nloglevel=error\n"
},
{
"path": "SOLUTIONS for Jotto Context Challenges/README.md",
"chars": 4504,
"preview": "# Jotto\n### A React app with hooks and contexts used to demonstrate testing\n\n## Branches\n\n* `master`\n\n This branch rep"
},
{
"path": "SOLUTIONS for Jotto Context Challenges/package.json",
"chars": 851,
"preview": "{\n \"name\": \"jotto-hooks\",\n \"version\": \"0.1.0\",\n \"private\": true,\n \"dependencies\": {\n \"axios\": \"^0.19.0\",\n \"pro"
},
{
"path": "SOLUTIONS for Jotto Context Challenges/public/index.html",
"chars": 2147,
"preview": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\" />\n <link rel=\"shortcut icon\" href=\"%PUBLIC_URL%/"
},
{
"path": "SOLUTIONS for Jotto Context Challenges/public/manifest.json",
"chars": 497,
"preview": "{\n \"short_name\": \"React App\",\n \"name\": \"Create React App Sample\",\n \"icons\": [\n {\n \"src\": \"favicon.ico\",\n "
},
{
"path": "SOLUTIONS for Jotto Context Challenges/public/robots.txt",
"chars": 57,
"preview": "# https://www.robotstxt.org/robotstxt.html\nUser-agent: *\n"
},
{
"path": "SOLUTIONS for Jotto Context Challenges/src/App.css",
"chars": 492,
"preview": ".App {\n text-align: center;\n}\n\n.App-logo {\n animation: App-logo-spin infinite 20s linear;\n height: 40vmin;\n pointer-"
},
{
"path": "SOLUTIONS for Jotto Context Challenges/src/App.js",
"chars": 4605,
"preview": "import React from 'react';\nimport './App.css';\nimport hookActions from './actions/hookActions';\nimport languageContext f"
},
{
"path": "SOLUTIONS for Jotto Context Challenges/src/App.test.js",
"chars": 2471,
"preview": "import React from 'react';\nimport { mount } from 'enzyme';\nimport { findByTestAttr } from '../test/testUtils';\nimport Ap"
},
{
"path": "SOLUTIONS for Jotto Context Challenges/src/Congrats.js",
"chars": 845,
"preview": "import React from 'react';\n\nimport successContext from './contexts/successContext';\nimport languageContext from './conte"
},
{
"path": "SOLUTIONS for Jotto Context Challenges/src/Congrats.test.js",
"chars": 1819,
"preview": "import React from 'react';\nimport { mount } from 'enzyme';\n\nimport { findByTestAttr } from '../test/testUtils';\nimport C"
},
{
"path": "SOLUTIONS for Jotto Context Challenges/src/EnterSecretWordButton.js",
"chars": 1155,
"preview": "// Challenge #4: Enter Secret Word\nimport React from \"react\";\nimport PropTypes from \"prop-types\";\n\nimport stringsModule "
},
{
"path": "SOLUTIONS for Jotto Context Challenges/src/EnterSecretWordButton.test.js",
"chars": 2558,
"preview": "// Challenge #3: Give Up\n\nimport React from 'react';\nimport { mount } from 'enzyme';\n\nimport { findByTestAttr, checkProp"
},
{
"path": "SOLUTIONS for Jotto Context Challenges/src/GiveUpButton.js",
"chars": 1049,
"preview": "// Challenge #3: Give Up\nimport React from \"react\";\nimport PropTypes from \"prop-types\";\n\nimport stringsModule from \"./he"
},
{
"path": "SOLUTIONS for Jotto Context Challenges/src/GiveUpButton.test.js",
"chars": 2148,
"preview": "// Challenge #3: Give Up\n\nimport React from 'react';\nimport { mount } from 'enzyme';\n\nimport { findByTestAttr, checkProp"
},
{
"path": "SOLUTIONS for Jotto Context Challenges/src/GuessedWords.js",
"chars": 2007,
"preview": "import React from 'react';\n\nimport guessedWordsContext from './contexts/guessedWordsContext';\nimport languageContext fro"
},
{
"path": "SOLUTIONS for Jotto Context Challenges/src/GuessedWords.test.js",
"chars": 3262,
"preview": "import React from 'react';\nimport { shallow } from 'enzyme';\nimport { findByTestAttr } from '../test/testUtils';\nimport "
},
{
"path": "SOLUTIONS for Jotto Context Challenges/src/Input.js",
"chars": 1934,
"preview": "import React from 'react';\nimport PropTypes from 'prop-types';\n\nimport guessedWordsContext from './contexts/guessedWords"
},
{
"path": "SOLUTIONS for Jotto Context Challenges/src/Input.test.js",
"chars": 2845,
"preview": "import React from 'react';\nimport { mount } from 'enzyme';\n\nimport { findByTestAttr, checkProps } from '../test/testUtil"
},
{
"path": "SOLUTIONS for Jotto Context Challenges/src/LanguagePicker.js",
"chars": 607,
"preview": "import React from 'react';\nimport propTypes from 'prop-types';\n\nfunction LanguagePicker({ setLanguage }) {\n const langu"
},
{
"path": "SOLUTIONS for Jotto Context Challenges/src/LanguagePicker.test.js",
"chars": 1079,
"preview": "import React from 'react';\nimport { shallow } from 'enzyme';\n\nimport { findByTestAttr, checkProps } from '../test/testUt"
},
{
"path": "SOLUTIONS for Jotto Context Challenges/src/NewWordButton.js",
"chars": 1827,
"preview": "// Challenge #2: Reset Game\nimport React from \"react\";\nimport PropTypes from \"prop-types\";\n\nimport stringsModule from \"."
},
{
"path": "SOLUTIONS for Jotto Context Challenges/src/NewWordButton.test.js",
"chars": 3706,
"preview": "// Challenge #2: Reset Game\n\nimport React from 'react';\nimport { mount } from 'enzyme';\n\nimport { findByTestAttr, checkP"
},
{
"path": "SOLUTIONS for Jotto Context Challenges/src/SecretWordEntry.js",
"chars": 1532,
"preview": "// Challenge #4: Enter Secret Word\nimport React from \"react\";\nimport PropTypes from \"prop-types\";\n\nimport stringsModule "
},
{
"path": "SOLUTIONS for Jotto Context Challenges/src/SecretWordEntry.test.js",
"chars": 3712,
"preview": "import React from 'react';\nimport { mount } from 'enzyme';\n\nimport { findByTestAttr, checkProps } from '../test/testUtil"
},
{
"path": "SOLUTIONS for Jotto Context Challenges/src/SecretWordReveal.js",
"chars": 917,
"preview": "// Challenge #3: Give Up\nimport React from \"react\";\nimport PropTypes from \"prop-types\";\n\nimport stringsModule from \"./he"
},
{
"path": "SOLUTIONS for Jotto Context Challenges/src/SecretWordReveal.test.js",
"chars": 2001,
"preview": "// Challenge #3: Give Up\n\nimport React from 'react';\nimport { mount } from 'enzyme';\nimport { findByTestAttr, checkProps"
},
{
"path": "SOLUTIONS for Jotto Context Challenges/src/ServerError.js",
"chars": 692,
"preview": "// Challenge #5: Server Error\nimport React from \"react\";\n\nimport stringsModule from \"./helpers/strings\";\nimport language"
},
{
"path": "SOLUTIONS for Jotto Context Challenges/src/ServerError.test.js",
"chars": 1441,
"preview": "// Challenge #5: Server Error\n\nimport React from 'react';\nimport { mount } from 'enzyme';\nimport { findByTestAttr, check"
},
{
"path": "SOLUTIONS for Jotto Context Challenges/src/actions/hookActions.js",
"chars": 399,
"preview": "import axios from 'axios';\n\nexport const getSecretWord = async (setSecretWord, setServerError) => {\n // Challenge #5: S"
},
{
"path": "SOLUTIONS for Jotto Context Challenges/src/actions/hookActions.test.js",
"chars": 2934,
"preview": "import moxios from 'moxios';\n\nimport { getSecretWord } from './hookActions';\n\ndescribe('moxios tests', () => {\n beforeE"
},
{
"path": "SOLUTIONS for Jotto Context Challenges/src/contexts/guessedWordsContext.js",
"chars": 1808,
"preview": "import React from 'react'\n\n// no default value\nconst guessedWordsContext = React.createContext();\n\n/**\n * @function useG"
},
{
"path": "SOLUTIONS for Jotto Context Challenges/src/contexts/guessedWordsContext.test.js",
"chars": 748,
"preview": "import React from 'react';\nimport { shallow } from 'enzyme';\n\nimport { GuessedWordsProvider, useGuessedWords } from './G"
},
{
"path": "SOLUTIONS for Jotto Context Challenges/src/contexts/languageContext.js",
"chars": 70,
"preview": "import React from 'react';\n\nexport default React.createContext('en');\n"
},
{
"path": "SOLUTIONS for Jotto Context Challenges/src/contexts/successContext.js",
"chars": 810,
"preview": "import React from 'react';\n\nconst successContext = React.createContext();\n\n\n/**\n* @function useSuccess\n* @returns {array"
},
{
"path": "SOLUTIONS for Jotto Context Challenges/src/contexts/successContext.test.js",
"chars": 717,
"preview": "import React from 'react';\nimport { shallow, mount } from 'enzyme';\n\nimport successContext from './successContext';\n\n// "
},
{
"path": "SOLUTIONS for Jotto Context Challenges/src/helpers/index.js",
"chars": 463,
"preview": "/**\n * @method getLetterMatchCount\n * @param {string} guessedWord - Guessed word.\n * @param {string} secretWord - Secret"
},
{
"path": "SOLUTIONS for Jotto Context Challenges/src/helpers/index.test.js",
"chars": 702,
"preview": "import { getLetterMatchCount } from './';\n\ndescribe('getLetterMatchCount', () => {\n const secretWord = 'party';\n test("
},
{
"path": "SOLUTIONS for Jotto Context Challenges/src/helpers/strings.js",
"chars": 2219,
"preview": "const languageStrings = {\n en: {\n congrats: 'Congratulations! You guessed the word!',\n submit: 'Submit',\n gues"
},
{
"path": "SOLUTIONS for Jotto Context Challenges/src/helpers/strings.test.js",
"chars": 1429,
"preview": "import stringsModule from './strings';\nconst { getStringByLanguage } = stringsModule;\n\nconst strings = {\n en: { submit:"
},
{
"path": "SOLUTIONS for Jotto Context Challenges/src/index.css",
"chars": 366,
"preview": "body {\n margin: 0;\n font-family: -apple-system, BlinkMacSystemFont, \"Segoe UI\", \"Roboto\", \"Oxygen\",\n \"Ubuntu\", \"Can"
},
{
"path": "SOLUTIONS for Jotto Context Challenges/src/index.js",
"chars": 452,
"preview": "import React from 'react';\nimport ReactDOM from 'react-dom';\nimport './index.css';\nimport App from './App';\nimport * as "
},
{
"path": "SOLUTIONS for Jotto Context Challenges/src/integration_tests/enter_secret_word.test.js",
"chars": 1827,
"preview": "// Challenge #4: Enter Secret Word\nimport React from 'react';\nimport { mount } from 'enzyme';\n\nimport App from '../App';"
},
{
"path": "SOLUTIONS for Jotto Context Challenges/src/integration_tests/giveup.test.js",
"chars": 2712,
"preview": "// Challenge #3: Give Up\nimport React from 'react';\nimport { mount } from 'enzyme';\nimport hookActions from '../actions/"
},
{
"path": "SOLUTIONS for Jotto Context Challenges/src/integration_tests/guesses.test.js",
"chars": 2983,
"preview": "import React from 'react';\nimport { mount } from 'enzyme';\nimport { findByTestAttr } from '../../test/testUtils';\n\nimpor"
},
{
"path": "SOLUTIONS for Jotto Context Challenges/src/integration_tests/resetgame.test.js",
"chars": 1838,
"preview": "// Challenge #2: Reset Game\nimport React from 'react';\nimport { mount } from 'enzyme';\nimport hookActions from '../actio"
},
{
"path": "SOLUTIONS for Jotto Context Challenges/src/serviceWorker.js",
"chars": 4951,
"preview": "// This optional code is used to register a service worker.\n// register() is not called by default.\n\n// This lets the ap"
},
{
"path": "SOLUTIONS for Jotto Context Challenges/src/setupTests.js",
"chars": 151,
"preview": "import Enzyme, { shallow } from 'enzyme';\nimport EnzymeAdapter from 'enzyme-adapter-react-16';\n\nEnzyme.configure({\n ada"
},
{
"path": "SOLUTIONS for Jotto Context Challenges/test/testUtils.js",
"chars": 812,
"preview": "import checkPropTypes from 'check-prop-types';\n\n/**\n * Return node(s) with the given data-test attribute.\n * @param {Sha"
},
{
"path": "SOLUTIONS for Jotto Redux Hooks Challenges/.gitignore",
"chars": 320,
"preview": "# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.\n\n# dependencies\n/node_modules\n/.pn"
},
{
"path": "SOLUTIONS for Jotto Redux Hooks Challenges/.npmrc",
"chars": 38,
"preview": "fund=false\naudit=false\nloglevel=error\n"
},
{
"path": "SOLUTIONS for Jotto Redux Hooks Challenges/README.md",
"chars": 3807,
"preview": "# Jotto\n\n### A React app to demonstrate testing\n\n## Challenges\n\n### 1. Number of Guesses\n\n![Number of Guesses Wireframe]"
},
{
"path": "SOLUTIONS for Jotto Redux Hooks Challenges/package.json",
"chars": 1116,
"preview": "{\n \"name\": \"jotto\",\n \"version\": \"0.1.0\",\n \"private\": true,\n \"dependencies\": {\n \"@testing-library/jest-dom\": \"^5.1"
},
{
"path": "SOLUTIONS for Jotto Redux Hooks Challenges/public/index.html",
"chars": 2151,
"preview": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\" />\n <link rel=\"icon\" href=\"%PUBLIC_URL%/favicon.i"
},
{
"path": "SOLUTIONS for Jotto Redux Hooks Challenges/public/manifest.json",
"chars": 492,
"preview": "{\n \"short_name\": \"React App\",\n \"name\": \"Create React App Sample\",\n \"icons\": [\n {\n \"src\": \"favicon.ico\",\n "
},
{
"path": "SOLUTIONS for Jotto Redux Hooks Challenges/public/robots.txt",
"chars": 67,
"preview": "# https://www.robotstxt.org/robotstxt.html\nUser-agent: *\nDisallow:\n"
},
{
"path": "SOLUTIONS for Jotto Redux Hooks Challenges/src/App.css",
"chars": 564,
"preview": ".App {\n text-align: center;\n}\n\n.App-logo {\n height: 40vmin;\n pointer-events: none;\n}\n\n@media (prefers-reduced-motion:"
},
{
"path": "SOLUTIONS for Jotto Redux Hooks Challenges/src/App.js",
"chars": 3143,
"preview": "import { useEffect } from \"react\";\nimport { useSelector, useDispatch } from \"react-redux\";\nimport \"./App.css\";\n\n// Chall"
},
{
"path": "SOLUTIONS for Jotto Redux Hooks Challenges/src/App.test.js",
"chars": 1318,
"preview": "import React from \"react\";\nimport { mount } from \"enzyme\";\nimport { Provider } from \"react-redux\";\n\nimport { findByTestA"
},
{
"path": "SOLUTIONS for Jotto Redux Hooks Challenges/src/Congrats.js",
"chars": 712,
"preview": "import React from 'react';\nimport PropTypes from 'prop-types';\n\n/**\n * Functional react component for congratulatory mes"
},
{
"path": "SOLUTIONS for Jotto Redux Hooks Challenges/src/Congrats.test.js",
"chars": 1296,
"preview": "import React from 'react';\nimport { shallow } from 'enzyme';\n\nimport { findByTestAttr, checkProps } from '../test/testUt"
},
{
"path": "SOLUTIONS for Jotto Redux Hooks Challenges/src/EnterWordButton.js",
"chars": 643,
"preview": "// Challenge #4: Enter Secret Word\nimport React from \"react\";\nimport PropTypes from \"prop-types\";\n\nconst EnterWordButton"
},
{
"path": "SOLUTIONS for Jotto Redux Hooks Challenges/src/EnterWordButton.test.js",
"chars": 2055,
"preview": "// Challenge #4: Enter Secret Word\nimport React from 'react';\nimport { shallow } from 'enzyme';\n\nimport { findByTestAttr"
},
{
"path": "SOLUTIONS for Jotto Redux Hooks Challenges/src/EnterWordForm.js",
"chars": 1205,
"preview": "// Challenge #4: Enter Secret Word\nimport React, { useState } from \"react\";\nimport PropTypes from \"prop-types\";\n\nexport "
},
{
"path": "SOLUTIONS for Jotto Redux Hooks Challenges/src/EnterWordForm.test.js",
"chars": 2789,
"preview": "// Challenge #4: Enter Secret Word\nimport React from \"react\";\nimport { shallow } from \"enzyme\";\n\nimport { findByTestAttr"
},
{
"path": "SOLUTIONS for Jotto Redux Hooks Challenges/src/GuessedWords.js",
"chars": 1545,
"preview": "import React from 'react';\nimport PropTypes from 'prop-types';\n\nconst GuessedWords = (props) => {\n let contents\n if (p"
},
{
"path": "SOLUTIONS for Jotto Redux Hooks Challenges/src/GuessedWords.test.js",
"chars": 2459,
"preview": "import React from 'react';\nimport { shallow } from 'enzyme';\nimport { findByTestAttr, checkProps } from '../test/testUti"
},
{
"path": "SOLUTIONS for Jotto Redux Hooks Challenges/src/Input.js",
"chars": 1720,
"preview": "import React from \"react\";\nimport PropTypes from \"prop-types\";\nimport { useSelector, useDispatch } from \"react-redux\";\n\n"
},
{
"path": "SOLUTIONS for Jotto Redux Hooks Challenges/src/Input.test.js",
"chars": 2914,
"preview": "import React from 'react';\nimport { mount } from 'enzyme';\nimport { findByTestAttr, checkProps, storeFactory } from '../"
},
{
"path": "SOLUTIONS for Jotto Redux Hooks Challenges/src/NewWordButton.js",
"chars": 803,
"preview": "// Challenge #2: Reset Game\n\nimport React from 'react';\nimport PropTypes from 'prop-types';\n\n/**\n * Functional react com"
},
{
"path": "SOLUTIONS for Jotto Redux Hooks Challenges/src/NewWordButton.test.js",
"chars": 2034,
"preview": "// Challenge #2: Reset Game\n\nimport React from 'react';\nimport { shallow } from 'enzyme';\n\nimport { findByTestAttr, chec"
},
{
"path": "SOLUTIONS for Jotto Redux Hooks Challenges/src/SecretWordReveal.js",
"chars": 980,
"preview": "// Challenge #3: Give Up Button\nimport React from \"react\";\nimport PropTypes from \"prop-types\";\n\n/**\n * Functional react "
},
{
"path": "SOLUTIONS for Jotto Redux Hooks Challenges/src/SecretWordReveal.test.js",
"chars": 1493,
"preview": "// Challenge #3: Give Up Button\n\nimport React from \"react\";\nimport { shallow } from \"enzyme\";\n\nimport { findByTestAttr, "
},
{
"path": "SOLUTIONS for Jotto Redux Hooks Challenges/src/ServerError.js",
"chars": 301,
"preview": "// Challenge #5: Server Error\nimport React from 'react';\n\nexport default (props) => {\n return (\n <div data-test=\"com"
},
{
"path": "SOLUTIONS for Jotto Redux Hooks Challenges/src/ServerError.test.js",
"chars": 674,
"preview": "// Challenge #5: Server Error\nimport React from 'react';\nimport { shallow } from 'enzyme';\n\nimport { findByTestAttr } fr"
},
{
"path": "SOLUTIONS for Jotto Redux Hooks Challenges/src/TotalGuesses.js",
"chars": 560,
"preview": "// Challenge #1: Number of Guesses\n\nimport React from 'react';\nimport PropTypes from 'prop-types';\n\n/**\n * Functional re"
},
{
"path": "SOLUTIONS for Jotto Redux Hooks Challenges/src/TotalGuesses.test.js",
"chars": 1046,
"preview": "// Challenge #1: Number of Guesses\n\nimport React from 'react';\nimport { shallow } from 'enzyme';\n\nimport { findByTestAtt"
},
{
"path": "SOLUTIONS for Jotto Redux Hooks Challenges/src/actions/__mocks__/index.js",
"chars": 135,
"preview": "module.exports = {\n ...jest.requireActual(\"..\"),\n __esModule: true,\n getSecretWord: jest.fn().mockReturnValue({ type:"
},
{
"path": "SOLUTIONS for Jotto Redux Hooks Challenges/src/actions/index.js",
"chars": 4563,
"preview": "import axios from \"axios\";\n\nimport { getLetterMatchCount } from \"../helpers\";\nimport { wordnikKey } from \"../config.js\";"
},
{
"path": "SOLUTIONS for Jotto Redux Hooks Challenges/src/actions/index.test.js",
"chars": 2007,
"preview": "import moxios from 'moxios';\n\nimport { storeFactory } from '../../test/testUtils';\nimport { getSecretWord } from './';\n\n"
},
{
"path": "SOLUTIONS for Jotto Redux Hooks Challenges/src/config.js.template",
"chars": 61,
"preview": "module.exports = {\n wordnikKey: \"YOUR_WORDNIK_KEY_HERE\",\n}"
},
{
"path": "SOLUTIONS for Jotto Redux Hooks Challenges/src/configureStore.js",
"chars": 251,
"preview": "import { createStore, applyMiddleware } from 'redux';\nimport ReduxThunk from 'redux-thunk';\nimport rootReducer from './r"
},
{
"path": "SOLUTIONS for Jotto Redux Hooks Challenges/src/guessWord.test.js",
"chars": 2979,
"preview": "import React from 'react';\nimport { mount } from 'enzyme';\nimport { Provider } from 'react-redux';\n\nimport App from './A"
},
{
"path": "SOLUTIONS for Jotto Redux Hooks Challenges/src/helpers/index.js",
"chars": 462,
"preview": "/**\n * @method getLetterMatchCount\n * @param {string} guessedWord - Guessed word.\n * @param {string} secretWord - Secret"
},
{
"path": "SOLUTIONS for Jotto Redux Hooks Challenges/src/helpers/index.test.js",
"chars": 709,
"preview": "import { getLetterMatchCount } from './';\n\ndescribe('getLetterMatchCount', () => {\n const secretWord = 'party';\n test("
},
{
"path": "SOLUTIONS for Jotto Redux Hooks Challenges/src/index.css",
"chars": 366,
"preview": "body {\n margin: 0;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',\n 'Ubuntu', 'Can"
},
{
"path": "SOLUTIONS for Jotto Redux Hooks Challenges/src/index.js",
"chars": 626,
"preview": "import React from 'react';\nimport ReactDOM from 'react-dom';\nimport { Provider } from 'react-redux';\n\nimport './index.cs"
},
{
"path": "SOLUTIONS for Jotto Redux Hooks Challenges/src/integration.test.js",
"chars": 4097,
"preview": "import { storeFactory } from '../test/testUtils';\nimport { guessWord } from './actions';\nimport { setUserSecretWord } fr"
},
{
"path": "SOLUTIONS for Jotto Redux Hooks Challenges/src/reducers/gaveUpReducer.js",
"chars": 1165,
"preview": "// Challenge #3: Give Up Button\n\n/* NOTE: This is not the optimal way to track whether or not the user has given up. \n W"
},
{
"path": "SOLUTIONS for Jotto Redux Hooks Challenges/src/reducers/gaveUpReducer.test.js",
"chars": 770,
"preview": "// Challenge #3: Give Up Button\nimport { actionTypes } from '../actions';\nimport gaveUpReducer from './gaveUpReducer';\n\n"
},
{
"path": "SOLUTIONS for Jotto Redux Hooks Challenges/src/reducers/guessedWordsReducer.js",
"chars": 460,
"preview": "import { actionTypes } from \"../actions\";\n\n/**\n * @function guessedWordsReducer\n * @param {array} state - Array of guess"
},
{
"path": "SOLUTIONS for Jotto Redux Hooks Challenges/src/reducers/index.js",
"chars": 781,
"preview": "import { combineReducers } from 'redux';\nimport success from './successReducer';\nimport guessedWords from './guessedWord"
},
{
"path": "SOLUTIONS for Jotto Redux Hooks Challenges/src/reducers/secretWordReducer.js",
"chars": 419,
"preview": "import { actionTypes } from '../actions';\n\n/**\n * @function secretWordReducer\n * @param {string} state - State before re"
},
{
"path": "SOLUTIONS for Jotto Redux Hooks Challenges/src/reducers/serverErrorReducer.js",
"chars": 470,
"preview": "// Challenge #5: Server Error\nimport { actionTypes } from '../actions';\n\n/**\n * @function serverErrorReducer\n * @param {"
},
{
"path": "SOLUTIONS for Jotto Redux Hooks Challenges/src/reducers/serverErrorReducer.test.js",
"chars": 543,
"preview": "// Challenge #5: Server Error\nimport { actionTypes } from '../actions';\nimport serverErrorReducer from './serverErrorRed"
},
{
"path": "SOLUTIONS for Jotto Redux Hooks Challenges/src/reducers/successReducer.js",
"chars": 433,
"preview": "import { actionTypes } from \"../actions\";\n\n/**\n * @function successReducer\n * @param {boolean} state - previous state.\n "
},
{
"path": "SOLUTIONS for Jotto Redux Hooks Challenges/src/reducers/successReducer.test.js",
"chars": 577,
"preview": "import { actionTypes } from '../actions';\nimport successReducer from './successReducer';\n\ntest('when previous state is u"
},
{
"path": "SOLUTIONS for Jotto Redux Hooks Challenges/src/reducers/userEnterReducer.js",
"chars": 594,
"preview": "// Challenge #4: Enter Secret Word\nimport { actionTypes } from '../actions';\n\n/**\n * @function userEnterReducer\n * @para"
},
{
"path": "SOLUTIONS for Jotto Redux Hooks Challenges/src/reducers/userEnterReducer.test.js",
"chars": 1084,
"preview": "// Challenge #4: Enter Secret Word\nimport { actionTypes } from '../actions';\nimport userEnterReducer from './userEnterRe"
},
{
"path": "SOLUTIONS for Jotto Redux Hooks Challenges/src/reportWebVitals.js",
"chars": 362,
"preview": "const reportWebVitals = onPerfEntry => {\n if (onPerfEntry && onPerfEntry instanceof Function) {\n import('web-vitals'"
},
{
"path": "SOLUTIONS for Jotto Redux Hooks Challenges/src/setupTests.js",
"chars": 146,
"preview": "import Enzyme from 'enzyme';\nimport EnzymeAdapter from '@wojtekmaj/enzyme-adapter-react-17';\n\nEnzyme.configure({ adapter"
},
{
"path": "SOLUTIONS for Jotto Redux Hooks Challenges/test/testUtils.js",
"chars": 1368,
"preview": "import checkPropTypes from 'check-prop-types';\nimport { createStore, applyMiddleware } from 'redux';\n\nimport rootReducer"
}
]
// ... and 118 more files (download for full content)
About this extraction
This page contains the full source code of the flyrightsister/udemy-react-testing-projects GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 318 files (421.3 KB), approximately 114.8k tokens, and a symbol index with 103 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.