How to Test React Component Libraries With ts-jest

Project Source Code

Get the project source code below, and follow along with the lesson material.

Download Project Source Code

To set up the project on your local machine, please follow the directions provided in the README.md file. If you run into any issues with running the project source code, then feel free to reach out to the author in the course's Discord channel.

This lesson preview is part of the The newline Guide to Building a Company Component Library course and can be unlocked immediately with a \newline Pro subscription or a single-time purchase. Already have access to this course? Log in here.

This video is available to students only
Unlock This Course

Get unlimited access to The newline Guide to Building a Company Component Library, plus 70+ \newline books, guides and courses with the \newline Pro subscription.

Thumbnail for the \newline course The newline Guide to Building a Company Component Library

Testing a component library is similar to application testing. Our tests should resemble how consumers will actually use our library. Testing is a complex topic that deserves its own course, and we will just be scratching the surface here. In this module, we will be setting up a basic testing environment using React Testing Library and TS JEST. React Testing Library has several guiding principles that help ensure that your tests are as flexible and accurate as possible. TS JEST is a TypeScript preprocessor that ensures JEST is able to consume and type check our tests. Since TS JEST is a preprocessor, for JEST, the setup is similar to a non-touchg rip codebase. To start, let's add JEST and TS JEST as development dependencies. We'll also include the type declarations for JEST as well. While those are installing, let's include a new JEST config. We will want to include a default preset using TS JEST. To make it a little bit easier to run our testing here, let's replace the existing test, a subscript, to just call JEST. Next, we're going to be installing React Testing Library with an additional utility package, JESTON. JESTON provides some custom matches that allow us to write assertions in a clear and reliable way. Let's add the new dependencies with npm install saved_dev. We're going to install @testing_library_react and @testing_library_justON. To make those JESTON assertions available within JEST, let's create a new JEST setup.ts file. We will import @testing_library_justON. To make this a part of the environment within JEST, let's add this as a setup file. To help the type completion, let's include the JEST setup file in our TS config . If we include, we can reference JEST setup.ts. This now gives us a full test script environment to start testing. Let's commit our changes, save our progress, and in the next lesson, we're going to be creating a test suite for our button component.