Testing our code through unit tests.
Jest can be found at https://jestjs.io.
To learn how to integrate testing and Jest into our project we'll add a unit test for
Testing is only done in a development environment, so we'll install Jest as a devDependency. Run
yarn add jest --dev to install Jest.
Continuing from the last lesson, we'll be using TypeScript to write our tests. To include types for Jest we need to install the TypeScript package. Run
yarn add @types/jest --dev.
Jest natively doesn't know how to validate TypeScript types. To do this we'll need to install a plugin called
ts-jest by running
yarn add ts-jest --dev.
Next, we'll tell Jest to use ts-jest by using ts-jest's init script. Run
yarn ts-jest config:init which will create a new
Open this file and change the
jsdom will allow us to use browser-specific functionality inside the testing Node environment (for example, the
Finally, in our
package.json file, add a new script called test which runs Jest.
Writing our first test#
src/ directory create a new file called
useScroller.test.ts. Jest will automatically run files with
.test. in their file extension. Enter the following code: