Getting started with Puppeteer and Headless Chrome

Dependencies:

Node v7.6.0 or greater; Yarn; latest npm

Let’s get this started

Do this:

Navigate, using the command line, to the folder where you make project magic.

mkdir best-app-ever
cd best-app-ever
npm init

Wait for the dialog to print out in the command line and then press the ‘return’ key 11 times or however long it takes to get through the npm init dialogue.

THEN

yarn add puppeteer mocha chai

Open your app in your text editor.

Open package.json and edit the test command.

Remove the part that says

"echo "Error: no test specified" && exit 1"

and replace it with

mocha --timeout 60000 test/*/**.js --require chai/register-expect"

Let’s take a look at what the above line does.
First, mocha --timeout 60000 test/*/**.js has mocha run all of the tests that are in the test folder. I like to order my tests like this test/"name of the route"/"what it's testing.js"
Then there’s --require chai/register-expect. What this command does is registers ‘expect’ so we can use it to test things. Here, we’ll test whether or not the number of h1 elements with an href attribute for the home page url equals one. Wow, that’s a mouthful! It’s kind of an arbitrary test but it’s all ours, so love it!

Now mocha will look for javascript files in a folder inside of the test folder.

So, now we get to make those folders and that first test file.

Back in the command line:

mkdir test && mkdir test/home && touch test/home/homePage.js

Type this in homePage.js:

const puppeteer = require('puppeteer');

describe('Home Page', () => {
    it('Can go to the home page', async () => {
        const browser = await puppeteer.launch({headless: false});
        const page = await browser.newPage();
        await page.goto('http://www.puppeteer.fun/', {waitUntil: 'networkidle2'});
        await page.screenshot({path: './screenshots/homie.png'});
        let aTagsWithHomeHref = await page.$$('a[href="http://www.puppeteer.fun/"]');
        expect(aTagsWithHomeHref.length).to.eql(4);
        await browser.close();
    })
});

We’re going to take a screenshot of the homePage so we need to make a place for that little sailor to live.  In the command line:

mkdir screenshots

Now you should be ready to go!

In the command line run:

npm test

And that’s it. It should have ran the test and given you output to your terminal/command line. If not, check your work.

Congratulations, you just made your first puppeteer UI test!
Now, go crazy with it! Think of all the things you can make with it.

jscottchapman

About the Author

jscottchapman

Leave a Comment:

%d bloggers like this: