This video is available to students only

Jest

Testing our code through unit tests.

Jest can be found at https://jestjs.io.

As our library grows in popularity, contributors, and lines of code, it can become hard to ensure code is correct. There are many forms of code testing: unit tests, integration tests, end-to-end tests, smoke tests, etc. Jest is a JavaScript testing framework that can run different forms of testing, but the most common is unit tests. Unit tests are automated tests, run by the computer, that check if a section of code is correct. Usually, this is a function or method. Unit tests are quick, small tests that don't require outside systems (for example databases).

To learn how to integrate testing and Jest into our project we'll add a unit test for useScroller().

Installing Jest#

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 jest.config.js file.

Open this file and change the testEnvironment from node to jsdom. jsdom will allow us to use browser-specific functionality inside the testing Node environment (for example, the window object).

Finally, in our package.json file, add a new script called test which runs Jest.

Writing our first test#

In the 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:

 

This page is a preview of Creating React Libraries from Scratch

No discussions yet