This content originally appeared on DEV Community and was authored by Guilherme Ananias
How can you ensure that a modification on a component won't break the responsiveness on the user device? How can you ensure that emails you send won't break when you change something in your UI?
What is a Visual Regression Test?
A visual regression test is a kind of test that will ensure that the result of any modification in the respective component won't break how the final user will see it.
Talking about UI components, design systems, colors, pages, emails and anything else the final user could see can be tested against visual regression.
This gives us, developers and designers, the guarantee we won't suffer from any unwanted change.
Visual Regression Testing With Jest
To have this kind of test in your codebase, you will need two libraries: jest-image-snapshot and node-html-to-image.
As the jest-image-snapshot
docs says, you need to extends your expect
. Here's an example how you can do it:
// jest.setup.js
import { toMatchImageSnapshot } from 'jest-image-snapshot';
expect.extend({ toMatchImageSnapshot });
After that, you can use expect().toMatchImageSnapshot()
in any test of your codebase.
How we can write some kind of test that will test those snapshots? You can follow the code below:
// __tests__/Component.spec.(jsx|tsx)
import { render } from '@testing-library/react';
import htmlToImage from 'node-html-to-image';
import { Component } from '../Component';
it('match visually snapshot - or any good test message here', async () => {
const { container } = render(<Component />);
const image = await htmlToImage({
html: container.innerHTML,
});
expect(image).toMatchImageSnapshot();
});
After all, how this works?
In this case, the toMatchImageSnapshot
only accepts a JPG buffer, it's where the node-html-to-image
library enters. From a HTML string, the library will output a JPG buffer that will be used as what we expected in the test.
Similar to other snapshot tests, when you run it for the first time, it will produce a new folder called __image_snapshots__
, inside it will have the "snapshotted" image to be compared.
In case something goes wrong, the test will breaks and will produce a new folder, inside the __image_snapshots__
, called __diff_output__
. This folder will contain both the new and old images, side-by-side, that you can use to visualize the changes.
If you want to know more about how we test our UI, we are hiring!
We are a startup that enables shoppers to pay as they like. To make this possible, Woovi provides instant payment solutions for merchants to accept orders.
This content originally appeared on DEV Community and was authored by Guilherme Ananias
Guilherme Ananias | Sciencx (2023-03-07T13:41:21+00:00) Avoiding UI Regressions With Jest. Retrieved from https://www.scien.cx/2023/03/07/avoiding-ui-regressions-with-jest/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.