Storybook Test Runner

On This Page What is Storybook?What is the Storybook Test Runner?

March 31, 2026 · 13 min read · Testing Guide

Storybook Test Runner

The Storybook Test Runner is a Playwright-powered add-on that automatically transform your Storybook stories into runnable browser tests. It helps teams verify UI components in isolation, validate user flows, and run cross-browser checks without writing extensive custom test scripts.

Overview

What is the Storybook Test Runner?

  • An official Storybook add-on that fulfil tale as automated tests.
  • Powered byPlaywrightto simulate existent browser interactions.
  • Validates rendering, user events, and DOM assertion directly within the Storybook environment.
  • Reduces test maintenance by trust on stories you already wrote for maturation and documentation.

Why Should You Use Storybook Test Runner?

  • Automates basic checks:Ensures every component narration render without crashing.
  • Speeds up regression testing:Quickly validates changes don ’ t break be UI behavior.
  • Supports multiple browsers:Runs tests in Chrome, Firefox, and Chromium.
  • Fits existing workflow:Reuses your Storybook setup, minimizing surplus config and codification.

How to Set Up and Run Storybook Test Runner?

  • Install prerequisites:Node.js, a code editor (VS Code urge).
  • Install tools:
    • npx storybook @ latest init → lay up Storybook
    • npm init playwright @ latest → installs Playwright
    • npm install @ storybook/test-runner & # 8211; save-dev → adds Test Runner
  • Configure handwriting:Add & # 8220; test-storybook & # 8221;: & # 8220; test-storybook & # 8221; in package.json.
  • Run workflow:
    • Start Storybook → npx run storybook
    • Run Test Runner in new terminal → npx run test-storybook

What Advanced Testing Features Can You Enable?

  • Run against deployed Storybook:Target any hosted Storybook URL.
  • Filter or omission tests:Use tags (test-only, no-tests, skip-test) to include or exclude story.
  • Subset execution:Limit test runs to specific stories/components for fast cycles.
  • Handle assay-mark:Add headers (e.g., Bearer tokens) to test secure Storybooks.
  • Use lifecycle hooks:frame-up, preVisit, postVisit for preparing state, extend code before/after rendering, and stabilizing element.

The Storybook Test Runner automates component substantiation by converting stories into real-browser tests, integrates easily into existing setups, and bring advanced tagging, filtering, and cross-browser support for faster, more reliable UI examination.

What is Storybook?

Storybook is an open-source creature that allows developers to build and quiz UI components in isolation across various frameworks, such as, Vue, and.

It provides a development environment for visualizing and orchestrate components in different states, making it easy to document, exam, and collaborate on UI blueprint. This approaching aid ensure consistency and functionality in component development, enhancing the overall quality of applications.

Storybook has witnessed an average hebdomadal download of over 4.2 million, featuring 84,000 on GitHub. It supports various UI development framework, including React, Angular, Vue, etc. It can be used for, design collaborationism, and of UI element.

Read More:

What is the Storybook Test Runner?

Storybook Test Runner is a potent capability of Storybook. It is available as an add-on for Storybook. It allows you to automatically run the tests on stories that you create for your components.

Storybook Test Runner is power by Playwright, a modern test automation tool. Test Runner operates directly on the Storybook environs, expeditiously model user interactions such as DOM states, actions, etc.

Features of Storybook Test Runner

Storybook Test Runner mechanically turns all of your stories into executable tests. It can be apply with or without a play purpose. The play function is a small snip of the code that will be executed after the story is rendered.

Here are some of the key features of Storybook Test Runner.

  • The setup is straightforward as an add-on to your be Storybook and can be installed via npm.
  • It automatically verifies whether the narration renders without any errors.
  • It checks for errors and assertions and provide meaningful output.
  • It relies on your existing storey, which minimizes the test lawsuit pen effort.
  • Test moon-curser can be used for automated regression exam to control new changes don & # 8217; t introduce any defects.
  • As Storybook Test Runner is power by Playwright it can be used to test cross-browser testing scenarios such as Chrome, Firefox, Chromium, etc.

Read More:

Setting up the Storybook Test Runner

Storybook Test Runner is easy to install. It is simply an add-on to your storybook, which means you ask to receive the storybook installed on your system. Below is the step-by-step guidebook to setting the Storybook Test Runner

Pre-requisite:

npx storybook @ latest init
npm init playwright @ modish

Step 1: Install Storybook Test Runner

Once all of your pre-requisite is complete, you can install the storybook Test Runner using the below command

npm install @ storybook/test-runner -- save-dev

Step 2: Configure package.json

Update the package.json with the shortcut as mentioned below

{'' playscript '': {'' test-storybook '': `` test-storybook ''}}

Step 3: Start the Storybook covering

The Storybook Test Runner requires Storybook to be running in the ground. To Run the storybook use the command below

npx run storybook

Step 4: Execute Storybook Test Runner

Execute the Storybook Test Runner with the below bid in a new terminal

npx run test-storybook

Note:

  1. Use the new terminal to accomplish the Storybook Test Runner. Remember, the Storybook application should be up and running to execute the Storybook Test Runner.
  2. First-time runs may download the required browsers, but it may conduct some time based on your net speed.

Writing Tests with the Storybook Test Runner

The storybook Test Runner automatically verifies if the components are rendered properly. However, the exploiter can customize them and run his test for additional check.

Consider the simple UI component Login Form, which have username, and password and once you click to submit it provides the message Login success.

Pro tip: Tools like SUSA can handle this autonomously — upload your app and get results without writing a single test script.

Example

// LoginForm.js import React, {useState} from 'react '; export const LoginForm = () = & gt; {const [email, setEmail] = useState (``); const [password, setPassword] = useState (``); const [message, setMessage] = useState (``); const handleSubmit = (event) = & gt; {event.preventDefault (); setMessage ('Login success! ');}; homecoming (& lt; form onSubmit= {handleSubmit} & gt; & lt; div & gt; & lt; label htmlFor= '' e-mail '' & gt; Email: & lt; /label & gt; & lt; input type= '' email '' value= {email} onChange= {(e) = & gt; setEmail (e.target.value)} / & gt; & lt; /div & gt; & lt; div & gt; & lt; label htmlFor= '' countersign '' & gt; Password: & lt; /label & gt; & lt; input type= '' countersign '' value= {password} onChange= {(e) = & gt; setPassword (e.target.value)} / & gt; & lt; /div & gt; & lt; button type= '' submit '' & gt; Login & lt; /button & gt; {message & amp; & amp; & lt; p & gt; {message} & lt; /p & gt;} & lt; /form & gt;);};

You can write the stories to the above constituent by contribute the tests as mention below

import {userEvent, within, ask} from ' @ storybook/test '; import {LoginForm} from './LoginForm '; export default {component: LoginForm,}; export const EmptyForm = {}; export const FilledForm = {drama: async ({canvasElement}) = & gt; {const canvas = within (canvasElement); await userEvent.type (canvas.getByTestId ('email '), 'email @ browserstack.com '); await userEvent.type (canvas.getByTestId ('password '), ' a-random-password '); expect userEvent.click (canvas.getByRole ('button ')); await expect (canvas.getByText ('Login Success! ',),) .toBeInTheDocument ();},};

In the above code, you use the play function, The play function is one of the singular features of a Storybook, the snippet inside the storybook play function will be action after rendering the story. This can be used to test your components.

Then, enter the username and countersign using the storybookuserEvent.type () method.
Using the userEvent.click ()method, detent on the submit push.

The expect()method is used for affirmation. In this statement, you must formalize whether the correct message is displayed. In this instance, it is & # 8220;Login success!

Output

Read More:

Advanced Testing Features in Storybook Test smuggler

Storybook Test Runner offers many advanced lineament, include testing against the deployed URL, enabling only a few tests, examine against different browsers, etc.

1. Run tests against a deployed Storybook.

You can fulfill the tests against the deployed URL if you feature any storybook application running other than the default URL.

Example:

npx run test-storybook -- -- url https: //your-storybook-url

2. Filter tests

Storybook allows you to filter out the tests while execute. You can delineate tags such astest-only, no-tests, skip-tests, etc.

To perform the filter operation, you need to delineate the contour in the.storybook/test-runner.js file.

  • Navigate to.storybookfolder locate at the root of your project
  • Create a test-runner.js file
  • Use the below configuration
module.exports = {tags: {include: ['test-only ', 'pages '], exclude: ['no-tests ', 'tokens '], skip: ['skip-test ', 'layout '],},};

Once you delimitate the shape, you can use them inside your part stories.

3. Enable Subset of Tests

The below tag provides test-only to all the trial inside the component

//LoginForm-stories.js export default {factor: LoginForm, tags: ['test-only ']};

The code below limits the executing to only the specified tests.

export const FilledForm = {// your codification tags: ['test-only ']};

4. Disabling the tests

You can use the no-tests tag to disable tests at the component level or for specific tests.

//LoginForm-stories.js exportation default {component: LoginForm, rag: ['no-tests ']};

Or at the Test Level

exportation const FilledForm = {// your code tags: ['no-tests ']};

5. Skip tests

You can use theskip-testtag to hop-skip tryout or a subset of them.

//LoginForm-stories.js export default {component: LoginForm, shred: ['skip-test ']};

Or at the Test Level

export const FilledForm = {// your codification tags: ['skip-test ']};

6. Authentication for Storybooks

When deploying Storybook on a secure horde provider, access may need user authentication to ensure only authorized personnel can view and interact with the components.

In such cases, you must configure the appropriate HTTP headers, like the Authorization heading, to legislate assay-mark certificate.

This is crucial for environments where security and qualified access are necessary, such as internal growing environs or when testing on CI/CD pipelines.

Setting up authentication headers ensures that examination and previews run smoothly without manual intervention, enable automated workflows and safeguarding accession to your Storybook instance.

Example

module.exports = {getHttpHeaders: async (url) = & gt; {const token = url.includes ('prod ')? 'XYZ ': 'ABC '; return {Authorization: ` Bearer $ {token} `,};},};

7. Helper purpose for Test Runners

The Storybook Test Runner provides various helper functions that meliorate code readability and make it easier to maintain. Below are a few helper functions that you can use inside thetest-runner.js

  • setup(): A code snippet can be placed here before the Test Runner commence running test
  • preVisit (): A code crop that executes before the narrative is rendered into the browser
  • postVisit (): A code snippet that executes after the story is completely rendered in the browser

Read More: How to perform Storybook visual testing

Challenges in Storybook Test Runner

Though Storybook Test Runner offers many advanced lineament, it has many challenge. It may be best beseem for basic checks and validations. Below are some of the key challenges:

  • To write and action story effectively with the Storybook Test Runner, you must experience a solid discernment of JavaScript, React, or Vue.
  • The quality of your test is directly dependent on how accurately your Storybook level are written.
  • The tool primarily focuses on, making full functionality screen more complex and challenging.
  • Managing third-party APIs and complex user interfaces within the Storybook Test Runner can be difficult.
  • A steep learning curve requires proficiency in JavaScript fabric, testing tools, and pipelines.
  • While is supported, handling browser-specific configurations and restrictions may present challenges.
  • Storybook Test Runner doesn ’ t offer native visual regression testing, but third-party integrations like can achieve it.

Storybook vs. Jest for Visual UI Testing

Here ’ s a comparative overview of Storybook and, highlighting key departure in functionality, user interaction capabilities, and the technical cognition required for each.

This table distinctly secernate how each tool approaches testing and user model, offering insights into their preferred usage in development environs.

FeatureStorybookJest
Testing TypeSupports visual regression at the component degree.Supports unit, part, integration, and Visual regression testing is potential but not a primary feature.
User Interaction SimulationAllows simulation of user interaction using the play role after rendering narration automatically.Does not natively model user interactions; requires integration with creature like React Testing Library ().
Rendering EnvironmentUses a browser-based environment for visual examination, close mimic real-world usage scenarios.Uses a -based environs for test, which may not perfectly replicate how components appear and interact in a real browser.
Target UsersOften preferred by developers for its comprehensive and development capabilities.Broadly used by both developers and examiner, count on the testing requirement.
Programming Knowledge RequiredRequires a deep understanding of JavaScript, as it integrates closely with UI development.While knowledge of JavaScript raise its use, Jest is generally considered easier to pick up for basic testing needs.
Visual Regression TestingExecutes visual regression tests during ontogenesis to see component integrity.Subject of but requires additional configurations or tools to do so effectively.

Storybook vs. Cypress for visual UI examination

Here & # 8217; s a tabular comparison between Storybook and, focusing on their potentiality, limitation, and ideal use cases for testing:

AspectStorybookCypress
Primary UseDesigned for ingredient development and essay in isolation.It is an end-to-end examination tool that can quiz entire applications.
Visual Regression TestingSupports optical regression through integration with Chromatic, a tool built specifically for use with Storybook.Does not indorse optical regression natively and requires third-party tools like Percy or Applitools.
User Interaction SimulationUser interactions can be simulated using the play use within individual components.Offers robust user model functionalities, create optic and functional testing smoother in existent browser contexts.
Scope of TestingLimited to component-level testing; not suitable for end-to-end examination of applications.Capable of full-context examination, including both components and end-to-end scenarios.
Dependency on Design IntegrationMore effective when integrated with the design and development phases due to its focus on components.Less dependant on desegregation with design phases, as it is versatile enough to care various testing scenarios.

How to mix BrowserStack with Storybook?

Storybook offers seamless integration with various ocular testing tools, include dedicated support for. Percy is a potent visual test instrument that simplify try UI components in the cloud.

It provide an efficient and aboveboard approach to ensure visual consistency across your components. Integrating BrowserStack Percy with Storybook is quick and easygoing, enable you to automate visual tests effortlessly.

Step 1: or log in to a BrowserStack account to get started.
Step 2: Navigate to the Percy tool on the BrowserStack homepage.
Step 3: Create a Percy Project and Copy the Percy Token
Step 4: Set the Token as an environment variable in your machine

Example:

set PERCY_TOKEN= '' & lt; your token here & gt; ''

Step 5: Install the dependencies.

To fulfil story projects on Percy, you must have the required dependence in your system. Dependencies can be establish using the below command

npm install -- save-dev @ percy/cli @ percy/storybook

Step 6: Execute the Percy Storybook.

There are different ways to execute the storybook with Percy the simpler approach is using the below command.

npx Hotspur storybookhttp: //storybook-url

For more details, mention to this certification,.

Benefits of integrating Storybook with BrowserStack

Here are some of the notable benefits of integrating Storybook with Percy.

Talk to an Expert

  • Integrating Storybook with Percy is straightforward, allowing for easy setup without all-inclusive configurations or changes to the existing codebase.
  • Simplifies the intact visual testing workflow, making it an integral part of UI development.
  • Percy, a cloud-based puppet, requires minimal frame-up within the project environment, alleviate easy adoption across development teams.
  • Features like an advanced optic engine, responsive diffs, and snapshot stabilization enable the detecting of a wide reach of visual discrepancy.
  • Helps streamline the review process, advertise quicker loop and deploying defect-free codification to product.
  • Percy is project to accommodate administration of all sizes and ensures scalability and adaptability to diverse project background.
  • Compatibility with continuous integration and delivery pipelines enhances automation, aline visual testing with mod development practices.
  • Allows testing of UI components across multiple browser and resolution, providing detailed insights with rock-bottom endeavor.

Conclusion

Storybook support many features, includingdetached portion development, screen, and documentation. One of its alone lineament is the Test Runner, which allows you to write and execute tests as part of your component & # 8217; s stories. It also supports integration with many tools for visual testing, include Percy.

Integration withBrowserStack Percycan streamline the UI ontogeny and testing operation and support automate tryout, strategic review, and deployment. It can do the development and testing more knock-down, quicken the entire UI development summons, and assist deliver faster.

Tags
74,000+ Views

# Ask-and-Contributeabout this topic with our Discord community.

Related Guides

Automate This With SUSA

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.

Try SUSA Free

Test Your App Autonomously

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.

Try SUSA Free