Skip to content

Instantly share code, notes, and snippets.

@jasonraimondi
Created May 15, 2022 22:54
Show Gist options
  • Save jasonraimondi/8b0e8cbb575249c220e62bd7ae1ebcd7 to your computer and use it in GitHub Desktop.
Save jasonraimondi/8b0e8cbb575249c220e62bd7ae1ebcd7 to your computer and use it in GitHub Desktop.
const { patch } = require('cy2');
const cypress = require('cypress');
const fetch = require('node-fetch');
const [BROWSER = 'electron'] = process.argv.slice(2);
const {
CI_BUILD_ID,
CYPRESS_API_URL,
CYPRESS_WEB_URL,
CYPRESS_RECORD_KEY,
} = process.env;
async function fetchPreviousRunStats() {
const query = `
query($ciBuildId: String!) {
runs(filters: [{
key:"meta.ciBuildId",
value:$ciBuildId
}]) {
runId
specs {
claimedAt
spec
results {
stats {
failures
}
}
}
}
}`;
let totalClaimed = 0;
let totalUnclaimed = 0;
let totalFails = 0;
let totalRuns = 0;
const res = await fetch(CYPRESS_API_URL, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
query,
variables: { ciBuildId: CI_BUILD_ID },
}),
});
const { data } = await res.json();
if (data.runs) {
totalRuns = data.runs.length;
data.runs.forEach(run => {
logItLoudly(`${CYPRESS_WEB_URL}run/${run.runId}`)
if (run.specs) {
run.specs.forEach(spec => {
if (spec.claimedAt) {
totalClaimed++;
} else {
totalUnclaimed++;
}
if (spec && spec.results && spec.results.stats && spec.results.stats.failures > 0) {
totalFails += spec.results.stats.failures;
}
});
}
});
}
const result = {
totalRuns,
totalClaimed,
totalUnclaimed,
totalFails,
};
logItLoudly('SORRY-CYPRESS RUN HISTORY INFO', result);
return result;
}
async function runCypress() {
const cypressConfig = {
browser: BROWSER,
headless: true,
record: true,
parallel: true,
key: CYPRESS_RECORD_KEY,
reporter: 'list',
group: BROWSER,
ciBuildId: CI_BUILD_ID,
env: {
configFile: 'github',
ci: true,
},
};
logItLoudly('CYPRESS RUN CONFIG', cypressConfig);
const result = await cypress.run(cypressConfig);
if (result.failures) {
throw new Error(`could not execute tests: ${JSON.stringify(result.message)}`);
}
return result.totalFailed ?? 0;
}
function logItLoudly(title, result) {
console.log(`\n\n==== ${title} ====\n`);
if (result) console.log(result);
}
async function main() {
await patch(CYPRESS_API_URL);
const { totalRuns, totalUnclaimed, totalFails } = await fetchPreviousRunStats();
if (totalRuns > 0 && totalUnclaimed === 0 && totalFails > 0) {
logItLoudly('there are no tests left to run, and we had a previous failure');
process.exit(1);
return;
}
const totalFailed = await runCypress();
if (totalFailed > 0) {
throw new Error(`totalFailed specs: ${totalFailed}`);
}
}
main().catch(err => {
logItLoudly("SCRIPT RUN FAILURE", err.message);
process.exit(1);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment