How to Use Jest with Storybook for Testing TypeScript Components



April 19, 2023


April 19, 2023

Developers have an unwavering desire to craft software that operates seamlessly and effortlessly. The key to achieving this goal lies in meticulous testing. And so, we present this exclusive post tailored to your needs!

Join us as we explore the world of TypeScript, Jest and Storybook - Setting up Jest and Storybook, crafting test cases, testing TypeScript components within Storybook, integrating Jest and Storybook, and a plethora of other enlightening topics.

In the blog, we explored the following pivotal subjects:

However, before delving into the intricacies, let us acquaint you with how the dynamic duo of Jest and Storybook can work wonders for your TypeScript testing endeavors.

The Storybook and Jest for TypeScript projects

Jest - a formidable JavaScript testing framework, enables developers to craft top-notch code for their applications while supporting Test Driven Development (TDD) and various other features. Similarly,

Storybook serves as a tool that simplifies the building of UI components, allowing developers to easily create, test, and refine them.

Together, Jest and Storybook form a robust toolset that enables developers to generate high-quality, scalable, maintainable, and easy-to-read code. Furthermore, Jest enables the testing of individual component logic, while Storybook facilitates the testing of component behavior and appearance.

Using Storybook and Jest with TypeScript can enhance the quality and productivity of your development process. 

Now that you comprehend the significance of Jest and Storybook in testing let's dive into the setup process.

Setting up Jest and Storybook:

To install Jest and Storybook, follow the steps below:

Step 1: Installing Jest and Storybook

1. Install Node.js and npm on your system if you haven't already done so.

2. Open your project directory in the terminal and install Jest and Storybook as dev dependencies by running the following command:

3. After the installation is complete, create a Jest configuration file by running the following command:

This will prompt you to answer a series of questions to configure Jest according to your project's needs.

4. Once Jest is configured, create a Storybook configuration file by running the following command:

This will create a basic Storybook configuration that you can customize according to your project's requirements.

5. Start Jest and Storybook by running the following commands in separate terminal windows:

This will start the Jest test runner and the Storybook development server respectively.

Note: Storybook can also be installed using yarn instead of npm. Additionally, it's important to note that Storybook requires your project to use a supported frontend framework, such as React, Vue.js, or Angular.

Step 2: Configure Jest to work with TypeScript

1. Install the required dependencies by running the following command: 

To test TypeScript code with Jest, you can use the ts-jest package, which is a TypeScript preprocessor for Jest. ts-jest compiles TypeScript code to JavaScript on the fly during test execution, allowing Jest to run the tests as if they were written in JavaScript.

2. Create a tsconfig.json file in your project root directory and add the following configuration:

3. Update your Jest configuration in the jest.config.js file with the following settings:

4. Finally, update your package.json file to add the following scripts:

So this will allow you to run Jest tests using TypeScript.

Now, let's find out how to integrate Jest and Storybook.

Step 3: Integrating Jest with Storybook

1. Install the @storybook/addon-storyshots package by running the following command

2. Update your .storybook/main.js configuration file to add the following settings:

3. Add the following script to your package.json file:

This will start Storybook and Jest in parallel.

4. Finally, run the following command to test your Storybook stories using Jest

This will run Jest tests against each Storybook story in your project.

And that's it! You should now have Jest and Storybook integrated and configured to work together.

How to write a unit test for the TypeScript component?

Here's an example of how you can write a unit test for a simple TypeScript component:

The above code defines a simple React component called “MyComponent” that accepts a single prop “text” of type string.

Now, let's write a unit test for this component using Jest:

The above test uses Jest's “describe” and “it” functions to define a test suite for the “MyComponent” component. It then uses the “render” function from the @testing-library/react package to render the component with a “text” prop, and finally, it uses Jest's “expect” function to assert that the rendered text matches the provided prop.

To run the above test, simply run the “npm test” command in your project's directory. If everything is set up correctly, you should see the test pass.

This is just a simple example, but Jest provides a lot more functionality for writing robust unit tests.

In general, it's a good idea to start with unit tests to ensure that individual pieces of code work as expected. From there, you can move on to integration tests to test how different pieces of code work together. 

Once you have a good understanding of how the system works, you can write acceptance tests to test the system as a whole. Finally, you can write performance tests to ensure that the system can handle the expected load.

Overall, the key is to write tests that are appropriate for the level of abstraction you're testing and to ensure that your tests cover all of the critical functions of your system.

Testing different test scenarios using Jest and Storybook

Jest with Storybook can be used to test a wide range of scenarios in a React web app, including,

1. Testing React UI components: 

Jest can be used to write unit tests for React components to ensure that they behave as expected, while Storybook can be used to visually display and test the components in a sandbox environment.

2. Testing different screen sizes and resolutions: 

Storybook's responsive viewports add-on can be used to test how components look and behave on different screen sizes and resolutions, ensuring that they are responsive and adaptable to various devices.

3. Testing component variations: 

Storybook's addon support can be used to create different variations of a component and test them all in one place, making it easy to identify and fix any issues.

4. Testing user interactions: 

Storybook's actions addon can be used to test user interactions such as clicks and form submissions, while Jest can be used to test the logic and state changes that result from those interactions.

5. Testing accessibility: 

Storybook's a11y add-on can be used to test the accessibility of components and identify any issues that need to be addressed.

6. Testing visual regression:

Jest and Storybook's snapshot testing features can be used to test for visual regression by comparing current and previous versions of a component and identifying any changes that may have occurred.

7. Testing authentication:

Jest can also be used to test authentication workflows, either by mocking the authentication flow or by using a library like “msw” to mock the backend responses. 

Let's discuss a simple example for testing authentication with Jest and Storybook

First, let's assume we have a “LoginForm” component that takes in a username and password and performs authentication against an API:

To test this component using Jest and Storybook, we can create a LoginForm.stories.tsx file in our src/stories directory:

This will create two stories for our “LoginForm” component: one with the default (empty) values, and one with pre-filled username and password fields.

Now, we can write our Jest tests for the “LoginForm” component. Let's create a LoginForm.test.tsx file in our src directory:

This test simulates a user entering their username and password, clicking the login button, and expecting the “onLogin” callback to be called. We're using the waitFor utility from the @testing-library/react package to wait for the “onLogin” callback to be called asynchronously.

Well, we now have a fully tested authentication workflow using Jest and Storybook.

Overall, Jest with Storybook can be used to test different scenarios in a React web app, helping to ensure that the app is high-quality, reliable, and visually appealing.

The key benefits of integrating Jest and Storybook for testing TypeScript code

Integrating Jest and Storybook for testing TypeScript code offers several key benefits:

1. Efficient testing: 

Jest and Storybook are both efficient testing tools that can help you catch errors early in the development process. By integrating the two, you can create a seamless testing experience that can help you identify and fix issues faster.

2. Test-driven development: 

Jest and Storybook support test-driven development (TDD) by allowing you to write tests first and then build your code to pass those tests. This can help you ensure that your code meets the desired specifications and behaves as expected.

3. Faster feedback loop: 

With Jest and Storybook, you can get faster feedback on the quality of your code, allowing you to make changes and fix issues before they become bigger problems.

4. Improved collaboration: 

Jest and Storybook can also help improve collaboration between developers, designers, and testers by providing a shared platform for testing and debugging code.

5. Consistency and scalability: 

Using Jest and Storybook together, you can ensure that your tests are consistent and scalable, making it easier to maintain and update your testing suite as your project grows and evolves.

And that is how integrating Jest and Storybook for testing TypeScript code can help you build higher-quality, more reliable applications with better testing coverage and faster feedback.

Make your TypeScript code testing a joy with Storybook and Jest

I hope you enjoyed this exciting journey of setting up Jest and Storybook for your TypeScript project! We aim to equip you with the skills to write unit tests for your TypeScript components, explore various test scenarios and delve into the myriad benefits of integrating Jest and Storybook into your project. 

But hold on; this isn't goodbye just yet!

There's still more to discover that can streamline your TypeScript project development, such as the option of integrating Storybook with Jest.

Exciting, right?

And that's just one of the many features that DhiWise React Builder offers to help take your web app development skills to the next level.

So what are you waiting for?

Start using DhiWise React Builder today and build your next React TypeScript project effortlessly!