#mocha and Google #puppeteer for #javascript and #html tests


Taken from Puppeteer GitHub:
Puppeteer is a Node library which provides a high-level API to control headless Chrome or Chromium over the DevTools Protocol.

Puppeteer - headless chromium API

Install puppeteer as a dev dependency if you use it only during development.
npm i --save-dev puppeteer
yarn add -dev puppeteer 


How to use puppeteer together with mocha to write JavaScript, HTML and CSS tests?

Let's say this is my HTML page: 

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <title>My Puppet</title>
    <script type="text/javascript" src="./build/amazingService.bundle.js"></script>
<p onClick=“beAmazed()”>Amazing Service</p>

  function beAmazed() {
    const amazingService = new AmazingService();
    amazingService.getAmazing().then(res => console.log(res));

To test document.querySelectorAll
page.$$eval(selector, pageFunction[, ...args])

To test document.querySelector

page.$eval(selector, pageFunction[, ...args])

To test whether a script is imported to a page as expected

page.evaluate(pageFunction, ...args)

Mocha and Puppeteer Tests

1) Serve your index.html over localhost using http-server or python -m SimpleHTTPServer.

2) Run npm test (which runs mocha)

describe(('test Amazing Service'), () => {
  let browser;
  const puppeteerOpts = {
    headless: true,
    slowMo: 100,
    timeout: 5000,

  before(async () => {
    browser = await puppeteer.launch(puppeteerOpts);

  after(async () => {
    await browser.close();

  it('should be amazing', async () => {
    const page = await browser.newPage();
    await page.goto('http://localhost:8000');
    expect(await page.title()).to.equal('My Puppet');
    const divsCounts = await page.$$eval('div', divs => divs.length);

    // the following syntax is needed if you use babel as of March 5th 2018
    const response = await page.evaluate(`(async () => {
      const amazingService = new AmazingService();
      const rate = await amazingService.getAmazing();
      return Promise.resolve({ rate });

There are many other functions of puppeteer. Please check out Google Chrome Puppeteer examples and Puppeteer API document to learn more about Puppeteer.

Thanks for reading!