Skip to content

Instantly share code, notes, and snippets.

@nettofarah
Created May 24, 2021 19:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nettofarah/879696055df516f410d36d8be5329f09 to your computer and use it in GitHub Desktop.
Save nettofarah/879696055df516f410d36d8be5329f09 to your computer and use it in GitHub Desktop.
Send Jest test results into Segment
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