Skip to content

Commit

Permalink
feat: puppeteer with watch (#315)
Browse files Browse the repository at this point in the history
  • Loading branch information
stoffeastrom committed Aug 15, 2018
1 parent 757da05 commit 31a7a29
Show file tree
Hide file tree
Showing 9 changed files with 132 additions and 69 deletions.
2 changes: 1 addition & 1 deletion aw.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ yargs
});
} else {
[...scopes.keys()]
.filter(k => (!k.includes('example-chrome') && !k.includes('example-protractor')))
.filter(k => (!k.includes('example-chrome') && !k.includes('example-protractor') && !k.includes('example-puppeteer')))
.map(k => scopes.get(k))
.forEach((p) => {
glob = [...glob, `${p}/test/**/*.spec.{js,ts}`];
Expand Down
24 changes: 15 additions & 9 deletions commands/node/src/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
/* eslint no-console: 0, max-len: 0, global-require: 0, import/no-dynamic-require: 0, object-curly-newline: 0, class-methods-use-this: 0 */
const EventEmitter = require('events');
const readline = require('readline');
const globby = require('globby');
const Mocha = require('mocha');
Expand All @@ -20,8 +21,9 @@ const getSourceContent = (filename) => {
return fs.readFileSync(filename, 'utf8');
};

class Runner {
constructor(argv, libs) {
class Runner extends EventEmitter {
constructor(argv, libs = { Mocha, NYC, importCwd, chokidar }) {
super();
this.argv = argv;
this.testFiles = [];
this.onlyTestFiles = [];
Expand Down Expand Up @@ -200,7 +202,7 @@ class Runner {
this.testFiles = globby.sync(this.argv.glob).map(f => path.resolve(f));
if (!this.testFiles.length) {
console.log('No files found for:', this.argv.glob);
process.exit(1);
this.exit(1);
}
return this;
}
Expand All @@ -225,13 +227,12 @@ class Runner {

onFinished(failures) {
this.isRunning = false;
this.emit('onFinished', failures);
process.on('exit', () => {
// safeSaveCache();
process.exit(failures);
this.exit(failures);
});
if (this.argv.exit) {
// safeSaveCache();
process.exit();
this.exit();
}
}

Expand Down Expand Up @@ -267,6 +268,7 @@ class Runner {
process.stdin.setEncoding('utf8');
process.stdin.on('keypress', (str) => {
if (str === '\u0003') {
this.emit('forceExit');
process.exit(0);
}
if (this.isRunning) {
Expand Down Expand Up @@ -339,7 +341,7 @@ class Runner {
if (this.argv.watch) {
return;
}
process.exit(1);
this.exit(1);
}
}

Expand Down Expand Up @@ -403,6 +405,10 @@ class Runner {
}
return this;
}

exit(code) {
process.exit(code);
}
}

const configure = (configPath) => {
Expand Down Expand Up @@ -445,7 +451,7 @@ const node = {
if (argv.presetEnv) {
require(argv.presetEnv);
}
const runner = new node.Runner(argv, { Mocha, NYC, importCwd, chokidar });
const runner = new node.Runner(argv);
runner
.addToMatchSnapshot()
.autoDetectDebug()
Expand Down
6 changes: 4 additions & 2 deletions commands/puppeteer/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,10 @@
},
"homepage": "https://github.com/qlik-oss/after-work.js#readme",
"dependencies": {
"globby": "8.0.1",
"mocha": "5.2.0"
"@after-work.js/node": "5.0.0-beta.2",
"@after-work.js/utils": "5.0.0-beta.2",
"puppeteer-core": "1.7.0",
"chrome-launcher": "0.10.2"
},
"files": [
"/src"
Expand Down
110 changes: 53 additions & 57 deletions commands/puppeteer/src/index.js
Original file line number Diff line number Diff line change
@@ -1,77 +1,73 @@
/* eslint global-require: 0, no-console: 0, import/no-unresolved: 0, import/no-extraneous-dependencies: 0, import/no-dynamic-require: 0, max-len: 0 */
const path = require('path');
const fs = require('fs');
const globby = require('globby');
const Mocha = require('mocha');
const options = require('./options');
/* eslint global-require: 0, import/no-dynamic-require: 0, object-curly-newline: 0 */
const chromeFinder = require('chrome-launcher/dist/chrome-finder');
const { getPlatform } = require('chrome-launcher/dist/utils');
const { Runner, configure } = require('@after-work.js/node/src/');
const nodeOptions = require('@after-work.js/node/src/options');
const utils = require('@after-work.js/utils');
const puppetOptions = require('./options');

process.on('unhandledRejection', (err) => {
console.error(`Promise Rejection:${err}`);
});
const options = Object.assign({}, nodeOptions, puppetOptions);

function runTests(files, mochaOpts) {
return (resolve) => {
const mocha = new Mocha(mochaOpts);
files.forEach(f => mocha.addFile(f));
mocha.run((failures) => {
resolve(failures);
});
};
}
function run(files, mochaOpts) {
return new Promise(runTests(files, mochaOpts));
}
const getChromeExecutablePath = async () => {
const installations = await chromeFinder[getPlatform()]();
if (installations.length === 0) {
throw new Error('Chrome not installed');
}
return installations[0];
};

const puppet = {
command: ['puppeteer', 'puppet'],
desc: 'Run tests with puppeteer',
builder(yargs) {
return yargs
.options(options)
.config('config', (configPath) => {
if (configPath === null) {
return {};
}
if (!fs.existsSync(configPath)) {
throw new Error(`Config ${configPath} not found`);
.config('config', configure)
.coerce('babel', utils.coerceBabel)
.coerce('nyc', (opt) => {
if (opt.babel) {
// opt.require.push('babel-register');
opt.sourceMap = false; // eslint-disable-line no-param-reassign
opt.instrumenter = './lib/instrumenters/noop'; // eslint-disable-line no-param-reassign
}
let config = {};
const foundConfig = require(configPath);
if (typeof foundConfig === 'function') {
config = Object.assign({}, foundConfig());
} else {
config = Object.assign({}, foundConfig);
}
return config;
return opt;
});
},
handler(argv) {
let puppeteer;
try {
puppeteer = require('puppeteer');
} catch (_) {
console.log('Could not load puppeteer');
const p = `${path.resolve(process.cwd())}/node_modules/puppeteer`;
console.log(`Trying: ${p}`);
try {
puppeteer = require(p);
} catch (__) {
console.log('Puppeteer could not be found by after-work.js! Please verify that it has been added as a devDependencies in your package.json');
process.exit(1);
}
}
const files = globby.sync(argv.glob);
if (!files.length) {
console.log('No test files found for:', argv.glob);
process.exit(1);
}
(async function launchAndRun() {
const puppeteer = require('puppeteer-core');
if (argv.presetEnv) {
require(argv.presetEnv);
}
const runner = new Runner(argv);
if (!argv.chrome.executablePath) {
argv.chrome.executablePath = await getChromeExecutablePath(); //eslint-disable-line
}
const browser = await puppeteer.launch(argv.chrome);
global.browser = browser;
global.page = await browser.newPage();
const failures = await run(files, argv.mocha);
await browser.close();
process.exit(failures);
const closeBrowser = () => {
(async function close() {
await browser.close();
}());
};
runner.on('onFinished', failures => runner.exit(failures));
runner.on('forceExit', closeBrowser);
runner.exit = (code) => {
if (argv.watch) {
return;
}
process.exitCode = code;
closeBrowser();
};
runner
.addToMatchSnapshot()
.autoDetectDebug()
.setupKeyPress()
.setTestFiles()
.setSrcFiles()
.require()
.run();
}());
},
};
Expand Down
7 changes: 7 additions & 0 deletions examples/puppeteer/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# puppeteer

## From the project root run

```shell
npx aw puppeteer -c examples/puppeteer/aw.config.js
```
4 changes: 4 additions & 0 deletions examples/puppeteer/aw.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
module.exports = {
glob: ['examples/puppeteer/test/*.spec.js'],
watchGlob: ['examples/puppeteer/test/*.{js,html}']
}
20 changes: 20 additions & 0 deletions examples/puppeteer/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"name": "@after-work.js/example-puppeteer",
"private": true,
"version": "5.0.0-beta.2",
"description": "Puppeteer example",
"main": "src/index.js",
"scripts": {
"lint": "eslint test"
},
"repository": {
"type": "git",
"url": "git+ssh://git@github.com/qlik-oss/after-work.js.git"
},
"author": "QlikTech International AB",
"license": "MIT",
"bugs": {
"url": "https://github.com/qlik-oss/after-work.js/issues"
},
"homepage": "https://github.com/qlik-oss/after-work.js#readme"
}
19 changes: 19 additions & 0 deletions examples/puppeteer/test/hello.fix.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<html lang="en">

<head>
<title>Test</title>
<meta charset="utf-8">
<base href="/">
<style>
#container {
width: 100%;
height: 100%;
}
</style>
</head>

<body>
<div id="container">hello world</div>
</body>

</html>
9 changes: 9 additions & 0 deletions examples/puppeteer/test/hello.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
/* global page */
describe('Puppeteer', () => {
it('should say hello world', async () => {
await page.goto(`file://${__dirname}/hello.fix.html`);
const container = await page.$('#container');
const txt = await (await container.getProperty('textContent')).jsonValue();
expect(txt).to.equal('hello world');
});
});

0 comments on commit 31a7a29

Please sign in to comment.