Puppeteer isn’t just for testing! How to generate great docs and ease development
Ever heard of Puppeteer? The tool that allows to control Google Chrome and Chromium based browsers programmatically.
The two main usages of puppeteer are end-2-end testing and site scraping but you can do so much more with it and this article is about 2 other possible usages.
Generating documentation
Creating documentation can be tedious work. Usually it requires to take screenshots of the app at very specific steps of its usage, moving those screenshots to a document to which you still need to add some comments.
And you will have to update all that when something changes in the app.
The perfect example of a un-satisfying and repetitive grunt work.
Bummer!
Luckily, if you have Puppeteer set up right, you can take screenshots and attach them the right comments in a programmatic fashion.
One way to achieve that is to create a function in the Jest environment file and expose it to your tests.
The function will take a screenshot of the page at the precise moment you want, store the path of the image in conjunction with the comments and at the end of the tests (at teardown) will compile all that as an HTML document.
The Jest environment should look somehow like this:
With a template to render the collected documentation more or less like:
And finally call the “writeDocs” function in your tests…
Once the tests are run, the teardown compiles the screenshots taken with the information you passed to the writeDocs function and produce a neat HTML file (see the teardown method in the code above).
Improve your front-end developer experience
Progresses in front-end tooling, like live-reloading and later hot-reloading, have eased development by avoiding most (but not all) need for reloading the browser window manually.
They are still edge-cases for which you might spend several minutes in order to reproduce a situation or state in the app.
Again un-satisfying and repetitive grunt work (and prone to mistakes).
The trick is to actually code those steps in your tests, launch them in a non-headless way (the default behaviour keeps the browser invisible, headless) and keep the browser open instead of closing it at the end of the test.
Additionally you may want to run this against your development environment (opposed to the production build that you should use when doing proper testing) in order to benefit from the hot-reloading once you’re at the state you wanted to reach.
So start your development server first (here running on port 3000) npm start
(or whatever suits your project) and then run jest TEST_KEEP_BROWSER=1 PORT=3000 npx jest --runInBand
.