Skip to content

Instantly share code, notes, and snippets.

@bokuweb
Created September 26, 2018 08:27
Show Gist options
  • Select an option

  • Save bokuweb/f9c704ade08d0a8af2e34eabb183f316 to your computer and use it in GitHub Desktop.

Select an option

Save bokuweb/f9c704ade08d0a8af2e34eabb183f316 to your computer and use it in GitHub Desktop.

Revisions

  1. bokuweb created this gist Sep 26, 2018.
    52 changes: 52 additions & 0 deletions mocha-puppeteer.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,52 @@
    const puppeteer = require('puppeteer');
    const path = require('path');
    const util = require('util');
    const mkdirp = require('mkdirp');
    const initMocha = require('./setup');

    const DEVICE_PROFILE = {
    viewport: {
    width: 1280,
    height: 400,
    deviceScaleFactor: 1,
    isMobile: false,
    hasTouch: false,
    isLandscape: false,
    },
    userAgent:
    'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36',
    };

    function handleConsole({ args }) {
    Promise.all(args.map(a => a.jsonValue())).then(args => {
    // process stdout stub
    let isStdout = args[0] === 'stdout:';
    isStdout && (args = args.slice(1));
    let msg = util.format(...args);
    !isStdout && (msg += '\n');
    process.stdout.write(msg);
    });
    }

    module.exports = async shouldWatch => {
    const browser = await puppeteer.launch({ args: ['--no-sandbox', '--disable-setuid-sandbox'] });
    const page = await browser.newPage();
    page.on('console', handleConsole);
    await page.emulate(DEVICE_PROFILE);
    await page.exposeFunction('takePicture', name => {
    const filename = path.resolve(__dirname, name);
    mkdirp.sync(path.dirname(filename));
    return page.screenshot({ path: filename, fullPage: true }).then(() => {});
    });
    await page.exposeFunction('exit', () => {
    if (!shouldWatch) process.exit(1);
    });
    await page.evaluateOnNewDocument(initMocha);
    await page.goto('file:///' + path.resolve(__dirname, 'index.html'));
    await page.waitForFunction(() => window.__mochaResult__, { timeout: 300000 });
    await page.evaluate(() => {
    if (window.__mochaResult__.result.stats.failures) exit();
    return window.__mochaResult__;
    });
    await browser.close();
    };