Expect Storybook actions in Cypress

How to test stories' actions in Cypress

Jonathan Gelin
2 min readApr 13, 2022

Using Cypress to test your stories is really nice if you want to test your UI components in isolation.

Problem

In Storybook, you can use the addon Actions for listening and dispatching your component events. However, it is hard to test because these actions are not accessible by Cypress.

To solve this issue, we will have to make these actions accessible by Cypress!

Solution

Step One: Listen for Storybook actions and dispatch them to the Document Element

Let’s take a simple story on a button:

When the button is clicked, an action named clicked will be sent with the argument Button Clicked

The goal now will be to catch this action and transfer it to the DOM. To do so, we can create a util function like:

In Storybook, to be able to communicate across addons, there is a global channel that you can listen to.

So we can subscribe to the action events and then dispatch them directly in the Document Element.

To activate this listener, you can simply call this function in your ./storybook/preview.ts file.

Step Two: Catch these events in Cypress and assert them.

In Cypress, you can listen to Element events just by adding a listener on the Element itself.

We use a Cypress Stub to be able to spy when the action is called and with what arguments.

Then we can just use common Sinon assertions to validate what happened.

Bonus: Create a Cypress custom command

You can create a Custom Cypress Command to avoid repetition:

Then you can use it just by doing:

Hope this Helps!

Looking for some help? 🤝
Connect with me on TwitterLinkedIn Github

--

--

Jonathan Gelin
Jonathan Gelin

Written by Jonathan Gelin

Write & Share about SDLC/Architecture in Ts/Js, Nx, Angular, DevOps, XP, Micro Frontends, NodeJs, Cypress/Playwright, Storybook, Tailwind • Based in 🇪🇺

No responses yet