Skip to content

Instantly share code, notes, and snippets.

@Toxicable
Last active March 28, 2018 21:07
Show Gist options
  • Save Toxicable/b5b95110864b2b61557f4e9ab90f4146 to your computer and use it in GitHub Desktop.
Save Toxicable/b5b95110864b2b61557f4e9ab90f4146 to your computer and use it in GitHub Desktop.
import { ChildProcess, spawn } from 'child_process';
import * as execa from 'execa';
const nodeCleanup = require('node-cleanup');
const terminate = require('terminate');
process.env.NODE_ENV = 'e2e';
let childProcesses: ChildProcess[] = [];
function start(cmd: string) {
const proc = execa.shell(cmd);
childProcesses.push(proc);
proc.stdout.pipe(process.stdout);
proc.stderr.pipe(process.stderr);
return proc;
}
function emitsToken(proc: ChildProcess, token: string) {
return new Promise<ChildProcess>((resolve, reject) => {
proc.stdout.on('data', data => {
if (data.toString().includes(token)) {
resolve();
}
});
proc.stderr.on('error', err => reject(err));
});
}
function terminatePromise(proc: ChildProcess) {
return new Promise((resolve, reject) => {
terminate(proc.pid, err => {
if (err) {
reject(err);
} else {
resolve();
}
});
});
}
let cypressStarted = false;
Promise.all([
emitsToken(start('some server'), 'some token'),
emitsToken(start('some server'), 'some token '),
emitsToken(start('ng serve --prod --environment=e2e'), 'webpack: Compiled successfully'),
])
.then(processes => {
console.log('processes stable, starting Cypress');
cypressStarted = true;
const cypress = start('yarn e2e');
cypress.once('exit', exitCode => {
console.log('Cypress done');
Promise.all(childProcesses.map(p => terminatePromise(p)))
.then(() => {
process.exit(exitCode);
})
.catch(err => {
console.log(err);
process.exit(exitCode);
});
});
})
.catch(err => process.exit(1));
// if we're not built before 5 minutes
setTimeout(() => {
if (!cypressStarted) {
process.exit(1);
}
}, 1000 * 60 * 5); // 10 minutes
nodeCleanup((exitCode, signal) => {
console.log('');
console.log('CLEANING UP');
if (signal) {
Promise.all(childProcesses.map(p => terminatePromise(p)))
.then(() => {
process.kill(process.pid, signal);
})
.catch(err => {
console.log(err);
process.kill(process.pid, signal);
});
nodeCleanup.uninstall(); // don't call cleanup handler again
return false;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment