Storybook : React standalone component testing

Sachin Joshi
3 min readMay 3, 2022

--

Well, we often write unit test cases for React components using either React Testing Library or Jest and Enzyme where we actually test DOM rendering.

But sometimes… We think rather than just checking on DOM renderings for e.g. if a particular div is loaded or not, if we could actually test the components by allowing it to run individually, then development would be much easier. Another scenario we could think of here is, if you want to have a QA cycle of your react component before integrating it in the actual screen/ container application. Storybook is the best option for these scenarios.

Let’s see how we can configure the Storybook and make use of it…

  1. I have created react project named react_app using below command

npx create-react-app react_app

2. Run the command npx sb init in the root folder of your react project.

Please note this command will not work on empty projects/folders.

Once storybook is installed it will create a new folder .storybook in your react application as in the below screenshot.

You can change the paths of your stories by changing configuration in main.js

You will also notice stories folder created in src folder with some sample functional components and their respective stories saved in files with .stories.jsx extensions. You can use .tsx in case of typescript.

3. To run the storybook in development mode use the command

npm run storybook

After running this command http://localhost:6006/?path=/story/example-introduction--page gets opened in browser which is the default storybook for your react project.

4. Let me showcase to you one of the default component’s storybook.

I have expanded the Header component from the left panel with the logged in option. It will render the view that is expected when the Header component receives user details.

Sample for Header stories you can find in <Project_folder>/src/stories/Header.stories.jsx

So that’s all about Storybook configuration in local environment. You can explore more by writing your own component stories using Storybook.

5. Deployment of storybook to environments other than local

You can use the npm run build-storybook command to generate a static build of a storybook and make index.html within the build folder accessible to users.

You can find more documentation on storybook at https://storybook.js.org/docs/react/get-started/introduction.

Hope you like the topic. Follow me for more web ui npm packages that will surely help your application development easier.

--

--

Sachin Joshi
Sachin Joshi

Written by Sachin Joshi

follow me for more topics on Java, RestAssured, GraphQL, Selenium, JavaScript, JUnit, Jenkins, GitHub Actions, WebUI, SOAP & VBScripts