Education
Last updated on Sep 15, 2023
Last updated on Apr 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:
The key benefits of integrating Jest and Storybook for TypeScript code
How you can make TypeScript code testing a joy with Jest and Storybook using DhiWise
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.
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.
To install Jest and Storybook, follow the steps below:
Install Node.js and npm on your system if you haven't already done so.
Open your project directory in the terminal and install Jest and Storybook as dev dependencies by running the following command:
1 npm install --save-dev jest @storybook/react 2
1 npx jest --init 2
This will prompt you to answer a series of questions to configure Jest according to your project's needs.
1 npx sb init 2
This will create a basic Storybook configuration that you can customize according to your project's requirements.
1 npm run test 2 npm run storybook 3
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.
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.
1 npm install --save-dev typescript ts-jest @types/jest 2
1 { 2 "compilerOptions": { 3 "target": "es5", 4 "module": "commonjs", 5 "esModuleInterop": true, 6 "sourceMap": true, 7 "jsx": "react", 8 "baseUrl": ".", 9 "paths": { 10 "*": ["types/*"] 11 } 12 } 13 } 14
1 module.exports = { 2 // ... 3 preset: 'ts-jest', 4 testEnvironment: 'jsdom', 5 testMatch: [ 6 '**/__tests__/**/*.ts?(x)', 7 '**/?(*.)+(spec|test).ts?(x)', 8 ], 9 }; 10
1 { 2 "scripts": { 3 "test": "jest" 4 } 5 } 6
So this will allow you to run Jest tests using TypeScript.
Now, let's find out how to integrate Jest and Storybook.
1 npm install --save-dev @storybook/addon-storyshots 2
1 module.exports = { 2 // ... 3 addons: ['@storybook/addon-storyshots'], 4 }; 5
1 { 2 "scripts": { 3 "test:storybook": "start-storybook -p 6006 & jest" 4 } 5 } 6
This will start Storybook and Jest in parallel.
1 npm run test:storybook 2
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.
Here's an example of how you can write a unit test for a simple TypeScript component:
1 // MyComponent.tsx 2 3 import React from 'react'; 4 5 type MyComponentProps = { 6 text: string; 7 }; 8 9 const MyComponent: React.FC<MyComponentProps> = ({ text }) => { 10 return <div>{text}</div>; 11 }; 12 13 export default MyComponent; 14
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:
1 // MyComponent.test.tsx 2 3 import React from 'react'; 4 import { render } from '@testing-library/react'; 5 import MyComponent from './MyComponent'; 6 7 describe('MyComponent', () => { 8 it('should render the provided text', () => { 9 const text = 'Hello, world!'; 10 const { getByText } = render(<MyComponent text={text} />); 11 expect(getByText(text)).toBeInTheDocument(); 12 }); 13 }); 14
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.
Jest with Storybook can be used to test a wide range of scenarios in a React web app, including,
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.
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.
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.
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.
Storybook's a11y add-on can be used to test the accessibility of components and identify any issues that need to be addressed.
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.
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:
1 import React, { useState } from 'react'; 2 import axios from 'axios'; 3 4 interface LoginFormProps { 5 onLogin: () => void; 6 } 7 8 export const LoginForm: React.FC<LoginFormProps> = ({ onLogin }) => { 9 const [username, setUsername] = useState(''); 10 const [password, setPassword] = useState(''); 11 12 const handleSubmit = async (event: React.FormEvent) => { 13 event.preventDefault(); 14 15 try { 16 const response = await axios.post('/api/login', { 17 username, 18 password, 19 }); 20 21 if (response.status === 200) { 22 onLogin(); 23 } 24 } catch (error) { 25 console.error('Login failed:', error.message); 26 } 27 }; 28 29 return ( 30 <form onSubmit={handleSubmit}> 31 <label> 32 Username: 33 <input 34 type="text" 35 value={username} 36 onChange={(event) => setUsername(event.target.value)} 37 /> 38 </label> 39 <label> 40 Password: 41 <input 42 type="password" 43 value={password} 44 onChange={(event) => setPassword(event.target.value)} 45 /> 46 </label> 47 <button type="submit">Login</button> 48 </form> 49 ); 50 }; 51
To test this component using Jest and Storybook, we can create a LoginForm.stories.tsx file in our src/stories directory:
1 import React from 'react'; 2 import { action } from '@storybook/addon-actions'; 3 import { LoginForm } from '../LoginForm'; 4 5 export default { 6 title: 'LoginForm', 7 component: LoginForm, 8 }; 9 10 export const Default = () => <LoginForm onLogin={action('onLogin')} />; 11 12 export const FilledOut = () => ( 13 <LoginForm 14 onLogin={action('onLogin')} 15 initialValues={{ username: 'john.doe', password: 'password123' }} 16 /> 17 ); 18
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:
1 import React from 'react'; 2 import { render, fireEvent, waitFor } from '@testing-library/react'; 3 import { LoginForm } from './LoginForm'; 4 5 describe('LoginForm', () => { 6 it('should submit the form with the entered credentials', async () => { 7 const onLogin = jest.fn(); 8 9 const { getByLabelText, getByText } = render( 10 <LoginForm onLogin={onLogin} /> 11 ); 12 13 const usernameField = getByLabelText('Username:') as HTMLInputElement; 14 const passwordField = getByLabelText('Password:') as HTMLInputElement; 15 const loginButton = getByText('Login') as HTMLButtonElement; 16 17 fireEvent.change(usernameField, { target: { value: 'john.doe' } }); 18 fireEvent.change(passwordField, { target: { value: 'password123' } }); 19 20 fireEvent.click(loginButton); 21 22 await waitFor(() => expect(onLogin).toHaveBeenCalled()); 23 }); 24 }); 25
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.
Integrating Jest and Storybook for testing TypeScript code offers several key benefits:
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.
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.
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.
Jest and Storybook can also help improve collaboration between developers, designers, and testers by providing a shared platform for testing and debugging code.
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.
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!
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.
Tired coding all day?
Do it with a few clicks.