Created
May 24, 2021 19:06
-
-
Save nettofarah/879696055df516f410d36d8be5329f09 to your computer and use it in GitHub Desktop.
Send Jest test results into Segment
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fetch = require('node-fetch') | |
const ex = require('execa') | |
const writeKey = '<your_segment_write_key>' | |
const btoa = (val) => Buffer.from(val).toString('base64') | |
const getBranch = async () => | |
(await ex('git', ['branch', '--show-current'])).stdout | |
async function increment(metric, value = 0, tags = []) { | |
const event = { | |
event: metric, | |
properties: { | |
value, | |
tags, | |
type: 'count', | |
}, | |
userId: 'system', | |
} | |
return fetch(`https://api.segment.io/v1/track`, { | |
method: 'POST', | |
headers: { | |
'Content-Type': 'application/json', | |
'User-Agent': 'analytics-node-next/latest', | |
Authorization: `Basic ${btoa(writeKey)}`, | |
}, | |
body: JSON.stringify(event), | |
}) | |
} | |
class SegmentCustomReporter { | |
async onTestResult(_context, result) { | |
const branch = process.env.BUILDKITE_BRANCH || (await getBranch()) | |
const metrics = result.testResults.map((res) => { | |
return increment('test_run', 1, [ | |
`duration:${res.duration}`, | |
`status:${res.status}`, | |
`title:${res.title}`, | |
`full_name:${res.fullName}`, | |
`parent:${(res.ancestorTitles || []).join('.')}`, | |
`branch:${branch}`, | |
]) | |
}) | |
await Promise.all(metrics).catch(console.error) | |
} | |
} | |
module.exports = SegmentCustomReporter |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment