DEV Community

Cover image for Giving Jest-Preview a Spin
Matti Bar-Zeev
Matti Bar-Zeev

Posted on

Giving Jest-Preview a Spin

In this week’s post join me as I give jest-preview, a tool for debugging your Jest tests in the browser, a spin and try it out.

I’ve recently heard about this nice tool which is supposed to help in debugging Jest tests, called jest-preview.
What do they mean by “debugging” you ask? Well as you know when you test with Jest and say you’re using react-testing-lib to test your React components you do a lot of querying on what’s going on in the DOM with a lot of assumptions, and that’s a lot of info to keep in your head.
The creators of this tool thought the same and figured that if there was some sort of way to preview the test in the browser and let the developer use the devtools to inspect his outcome, it could help a lot.
I agree.

So let’s see how this tool works and what we can do with it. I’m gonna do my experimenting over my Pagination component which resides on the @pedalboard/components package.
Let’s go!


I start by installing the tool

yarn add jest-preview -D

Now the docs say that you can start debugging your tests with just adding 2 lines of code. That’s true… to the most part, let’s see why -
Let’s try that we a test I already got:

import {render} from '@testing-library/react';
...

describe('Pagination component', () => {
   it('should render', () => {
       const {getByText} = render(
           <Pagination
               pagesBuffer={5}
               totalPages={10}
               initialCursor={3}
               onChange={function (): void {
                   throw new Error('Function not implemented.');
               }}
           />
       );
       preview.debug();
       expect(getByText('[5]')).toBeInTheDocument();
       expect(getByText('PREV')).toBeInTheDocument();
       expect(getByText('NEXT')).toBeInTheDocument();
   });
});
Enter fullscreen mode Exit fullscreen mode

Ok, I’ve added the lines of code and I run my Jest command and… nothing appears to be changing. The test runs and passes but I don’t see any preview.

This is usually the point where I realize that the docs are a bit lacking. I don’t like it when “getting started” does not really get you started :(
It is time to start diving more into the docs.

It appears that in order to run the preview you need to run the tests with another command, that is the jest-preview command. I missed it somehow. Maybe since it is not written in the “Getting started” page. Nevermind.
I will add that to the npm scripts as they suggest here.

"scripts": {
       "test": "jest",
       ...
       "jest-preview": "jest-preview"
   },
Enter fullscreen mode Exit fullscreen mode

Running yarn jest-preview and my browser launches (yay!), and I see in the terminal that the process is listening on port 3336, but still no debugging.
This is what I get:

Image description

No preview found.
Please run:

preview.debug();
Enter fullscreen mode Exit fullscreen mode

BTW, on the terminal output I get these (typo-ish) messages:

Jest Preview Server listening on port 3336
[WARN] File not found:  /node_modules/jest-preview/cli/server/favicon.ico
[WARN] Please check if /node_modules/jest-preview/cli/server/favicon.ico is existed.
[WARN] If it is existed, likely you forget to setup the code transformation, or you haven't flushed the old cache yet. Try to run "./node_modules/.bin/jest --clearCache" to clear the cache.
Enter fullscreen mode Exit fullscreen mode

Whaa…..? Why should I care now about the favicon.ico? Oh well, but why do I get this message in the browser?
Too many questions at this early point, but this will not break me so soon. Let’s carry on.

In no particular place does it say that you need to run the jest-preview and then run the jest tests, but yes - that’s what you need to do, apparently. The flow I got it to work is as follows:

  1. Run jest-preview
  2. Run Jest tests
  3. Refresh the browser

Having it like so and you get your component in the browser. This is the initial test which simply renders the component and asserts some DOM elements:

Image description

That's pretty cool :)

I would like now to make something with a bit more value. I will render the component and click the “NEXT” button a few times and see in the preview that the “selected” CSS class is appended to the expected element.
Here is my test:

it('should click to go next', () => {
       render(<Pagination pagesBuffer={5} totalPages={10} initialCursor={3} onChange={() => {}} />);

       const nextBtn = screen.getByRole('button', {name: 'NEXT'});
       fireEvent.click(nextBtn);
       fireEvent.click(nextBtn);
       fireEvent.click(nextBtn);
       fireEvent.click(nextBtn);
       preview.debug();

       const sevenPageElement = screen.getByText('[7]');
       expect(sevenPageElement).toHaveClass('selected');
   });
Enter fullscreen mode Exit fullscreen mode

I’m now running the JEst in a watch mode, cause I would like to see the preview changes as I change the test (as the demo displays so nicely), and… nope, the browser does not refresh upon changes.
I refresh it myself, and sure enough I get the result I was expecting - the 7th page is selected:

Image description

Changing the test and saving it is running the Jest test again, but the preview does not get updated. I didn’t get it to work, so if you got any idea what I missed along the way please be sure to share with the rest of us.

So is it any good?

Well, it is nice that you can render your Jest tests in the browser and inspect the component’s DOM. When testing a UI component we usually assume a lot about the DOM our component creates and this preview allows us to actually see what’s going on and act accordingly.

To sum up, it is a cool tool that still needs some tweaks and adjustments, but I can totally see where this comes handy. Something to keep our eye on ;)

As always if you have any comments or questions be sure to leave them at the comments below so we can all learn from it.

Hey! If you liked what you've just read check out @mattibarzeev on Twitter 🍻

Photo by Glenn Carstens-Peters on Unsplash

Discussion (4)

Collapse
nvh95 profile image
Hung Viet Nguyen

Hi Matti,
Jest Preview (github.com/nvh95/jest-preview) author here 👋. Thank you very much for introducing Jest Preview on dev.to.

I am absolutely going to update and polish the docs after reading your feedback in your post, as well as looking at some other issues (fav.ico, automatic reload).

Jest Preview was born with a mission help frontend engineers lives easier, and help improving frontend application quality by encouraging them to write more tests.

Thank you very much.

P.S: If you guys have any issues while integrating with Jest Preview, please create an issue or reaching us on twitter @hung_dev or @JestPreview

Collapse
mbarzeev profile image
Matti Bar-Zeev Author

Hi @nvh95 :)
I think the project has real potential in making FE devs testing experience better and that's a great initiative - so thanks for making the effort!
I'm glad that my feedback found you and I will be sure to check any updates on the tool and update this post if needed.
Keep up the good work and thanks again :)

Collapse
rickvian profile image
Rickvian Aldi

i've going through the pain of doing lots of assumtion when writing FE unit tests,
looking forward for the update! awesome library!

Collapse
nvh95 profile image
Hung Viet Nguyen

Thank you for your kind words @rickvian. I already update the docs to make it less confusing for newcomers. I am working on the issue the snapshot does not “auto reload”, but I suspect it’s the issue with monorepo. I am also waiting for new feedback from you as well.

Please give it a try now. If your projects are open source, give me an url, I am more than happy to send a PR that integrate Jest Preview to yours. I believe you will love this library, the same way I Iove how my own library saves me a lot of time working with Jest.