Visual Regression Testing with Lost Pixel and Storybook
Testing is a crucial part of modern software development. One approach to testing is test-driven development (TDD), which emphasizes writing tests before writing code. While TDD is straightforward for backend applications, testing UI-centric applications can be more challenging. This is where Lost Pixel comes in – an open-source tool that helps identify regressions in the user interface with every push to the application.
What is Lost Pixel?
Lost Pixel is a visual regression testing tool that renders actual images of components and compares them to detect changes. This approach differs from snapshot testing, which represents components in a textual format. Lost Pixel currently supports Storybook, Ladle, Next.js, Gatsby, and Remix.
What is Storybook?
Storybook is a tool that optimizes React development workflow by isolating components, making development faster and easier. It provides a platform for coding building blocks independently, reducing bugs and surprises when combining them into meaningful applications. Storybook also provides free documentation of all components.
Setting up Storybook with React and Vite
To set up Storybook with React and Vite, create a new React project using Vite. Then, install Storybook and configure it to work with Vite. Once set up, you can run Storybook and see the pre-defined button components.
Introducing Lost Pixel
To introduce Lost Pixel into your repository, install it using npm. Then, create a lost-pixel.config.js file at the root of your Vite project, telling Lost Pixel where to find the Storybook components.
Creating GitHub Workflows
Create two GitHub workflows: lost-pixel-update.yml and lost-pixel-test.yml. The lost-pixel-update.yml workflow generates baselines for your Storybook components, while the lost-pixel-test.yml workflow tests for visual regressions on every push to the repository.
Generating Baselines
To generate baselines, run the lost-pixel-update.yml workflow. This will create a pull request with the changed components, which you can then merge into your repository.
Testing Visual Regressions
Once you’ve set up Lost Pixel and generated baselines, you can test for visual regressions. Make a change to one of your Storybook components, commit, and push to the remote repository. The lost-pixel-test.yml workflow will be triggered, and if there’s a regression, it will fail.
Using Lost Pixel in Your Projects
Lost Pixel provides an alternative method for UI regression testing, different from standard snapshot testing. If your project uses many Storybook components, you can explore Lost Pixel for detecting UI regressions. However, keep in mind that Lost Pixel requires additional .png images to be pushed to your repository.