Repository navigation
Ingesting From Jest
A Node service tested in-process under Jest (the service built in the test, driven with fastify.inject, its
dependencies faked with MSW) can have the report an in-process .NET run has, with no change to the service and none
to the tests: sequence diagrams of every call the test made and every call the service made, step bars with the
setup calls in a Setup partition, a note per expect, a retried test shown as its last attempt, and each call's
internal flow from the service's OpenTelemetry spans (4.4.0). A harness of five files writes three kinds of
file, and kronikol ingest makes the report from them.
The worked example is a Fastify 5 and Mercurius 16 GraphQL service whose resolver calls a payment provider (faked by
MSW) and a risk service (a local fake MSW passes through). Every file below ran as shown, and the report was checked,
with Node 22.22, Jest 30.5, Fastify 5.12, Mercurius 16.10, MSW 2.11, the OpenTelemetry JS SDK 2.11,
@opentelemetry/instrumentation-graphql 0.70, @opentelemetry/instrumentation-undici 0.32 and @fastify/otel 0.21
(plans/INGEST_FIDELITY_PLAN.harness/otel-jest/recipe in the repository, run with Kronikol 4.4.0).
The pieces are the owner's to change: another web framework needs its own inbound capture point, another fake its own outbound one. What has to hold is the contract each file writes, which Ingesting External Captures documents.
| File | Written by | What it holds |
|---|---|---|
kronikol-capture/tests.ndjson |
the Jest environment, and the expect wrapper |
Each test's start, its steps, its assertions and its end, with attempt on each, from every worker (the tests format) |
kronikol-capture/interactions-<worker>.ndjson |
the capture points | A request line and a response line per call, each stamped with the running test's id and with the trace and the span the call was made under (the interaction format) |
kronikol-capture/spans-<worker>.jsonl |
the tracing setup, after each test file | The file's spans, one OTLP/JSON TracesData object per line (Spans) |
Not .kronikol/: that folder above the report holds Kronikol's history ledger, whose
history.jsonl an input directory would take for a capture.
module.exports = {
testEnvironment: '<rootDir>/kronikol/environment.js',
setupFiles: ['<rootDir>/kronikol/setup.js'],
setupFilesAfterEnv: ['<rootDir>/kronikol/after-env.js'],
testMatch: ['<rootDir>/tests/*.test.js']
}A custom environment sees every test event. Each test gets an id stable across runs (its file and full name), set
on the test's global for the capture points; its beforeEach hooks are its Given step and its body its When
step, written when the test ends so each carries its status; a retry (jest.retryTimes) is the next attempt of
the same id, which the report shows as its last attempt with a retry 1 badge.
'use strict'
// Jest environment: one tests NDJSON line per test start, its steps and its end. Steps are kept until the
// test ends so each carries its status: beforeEach is the Given step (setup), the test body the When step.
const { TestEnvironment } = require('jest-environment-node')
const crypto = require('node:crypto')
const fs = require('node:fs')
const path = require('node:path')
const dir = process.env.KRONIKOL_DIR ?? 'kronikol-capture'
function fullName (test) {
const names = [test.name]
for (let block = test.parent; block && block.name !== 'ROOT_DESCRIBE_BLOCK'; block = block.parent) names.unshift(block.name)
return names.join(' › ')
}
function message (error) {
const e = Array.isArray(error) ? error[0] : error
return e?.stack ?? e?.message ?? String(e)
}
class KronikolEnvironment extends TestEnvironment {
constructor (config, context) {
super(config, context)
this.file = path.relative(process.cwd(), context.testPath).split(path.sep).join('/')
this.steps = []
fs.mkdirSync(dir, { recursive: true })
}
write (record) {
// One line per append: lines this short are written whole even with every worker appending to the file.
fs.appendFileSync(path.join(dir, 'tests.ndjson'), JSON.stringify(record) + '\n')
}
step (keyword, text) {
this.steps.push({ keyword, text, started: Date.now(), timestamp: new Date().toISOString() })
}
async handleTestEvent (event, state) {
const test = event.test ?? state.currentlyRunningTest
if (!test) return
const name = fullName(test)
const testId = crypto.createHash('sha256').update(`${this.file}|${name}`).digest('hex').slice(0, 32)
const attempt = test.invocations
switch (event.name) {
case 'test_start':
this.steps = []
// The capture points stamp every record with it; the Fastify hook binds it to each request.
this.global.__kronikolTestId = testId
this.global.__kronikolAttempt = attempt
this.write({ event: 'start', testId, testName: name, feature: this.file, sourceFile: this.file, attempt, timestamp: new Date().toISOString() })
break
case 'hook_start':
// Every beforeEach hook of the test is the one Given step, timed from the first.
if (event.hook.type === 'beforeEach' && this.steps.length === 0) this.step('Given', 'the test is set up')
break
case 'test_fn_start':
this.step('When', 'the test runs')
break
case 'test_done': {
const failed = test.errors.length > 0
this.steps.forEach((step, i) => {
const last = i === this.steps.length - 1
const next = this.steps[i + 1]
this.write({
event: 'step', testId, keyword: step.keyword, text: step.text, attempt, timestamp: step.timestamp,
status: failed && last ? 'failed' : 'passed',
durationMs: (next?.started ?? Date.now()) - step.started,
error: failed && last ? message(test.errors[0]) : undefined
})
})
this.write({
event: 'end', testId, attempt, timestamp: new Date().toISOString(),
status: failed ? 'failed' : 'passed', durationMs: test.duration,
error: failed ? message(test.errors[0]) : undefined
})
this.global.__kronikolTestId = undefined
this.global.__kronikolAttempt = undefined
break
}
}
}
}
module.exports = KronikolEnvironmentJest reports a test's beforeEach hooks one hook_start each (a test with one beforeEach of its own saw two), so
the first opens the step.
Inbound, Fastify announces every instance it creates on the fastify.initialization diagnostics channel, so the
harness adds its hooks there and no test registers anything. The onRequest hook runs the rest of the request
inside an AsyncLocalStorage scope holding the test the request arrived under, so a call the service makes after the
test moved on keeps its test. Outbound, MSW's lifecycle events see every call the service makes, mocked or passed
through.
Each call is stamped with trace.getActiveSpan()'s trace id and span id: the join to the spans. Under MSW the
listener runs inside the span the service made the call in (the resolver's), and in the Fastify hook inside the
request's.
'use strict'
// Capture points: every inbound request Fastify serves and every outbound call MSW sees becomes a
// request line and a response line of interactions-<worker>.ndjson, stamped with the running test's id and
// with the trace and span the call was made under, which joins it to the spans kronikol ingest --spans reads.
const { AsyncLocalStorage } = require('node:async_hooks')
const crypto = require('node:crypto')
const dc = require('node:diagnostics_channel')
const fs = require('node:fs')
const path = require('node:path')
const { trace } = require('@opentelemetry/api')
const dir = process.env.KRONIKOL_DIR ?? 'kronikol-capture'
const file = path.join(dir, `interactions-${process.env.JEST_WORKER_ID ?? '1'}.ndjson`)
const SERVICE = process.env.KRONIKOL_SERVICE ?? 'Service'
const requestScope = new AsyncLocalStorage()
/** The test the request being served arrived under, else the test running now. */
const testId = () => requestScope.getStore()?.testId ?? globalThis.__kronikolTestId ?? 'outside-any-test'
function write (record) {
fs.mkdirSync(dir, { recursive: true })
fs.appendFileSync(file, JSON.stringify(record) + '\n')
}
/** The ids of the call: its own, its test's, and the span it is made under. */
function begin () {
const span = trace.getActiveSpan()?.spanContext()
return { requestResponseId: crypto.randomUUID(), testId: testId(), activityTraceId: span?.traceId, activitySpanId: span?.spanId }
}
// Inbound: Fastify announces every instance it creates on this channel, so no test registers anything.
function onFastify ({ fastify }) {
const uri = request => `http://${request.hostname}${request.url}`
const writeRequest = request => {
if (request.kronikol.written) return
request.kronikol.written = true
const { written, at, ...call } = request.kronikol
write({ ...call, type: 'Request', method: request.method, uri: uri(request), serviceName: SERVICE, callerName: 'Test',
content: request.body === undefined ? undefined : JSON.stringify(request.body), timestamp: at })
}
fastify.addHook('onRequest', (request, reply, done) => {
// Everything the service does for this request keeps the test it arrived under, even past the test's end.
requestScope.run({ testId: testId() }, () => {
request.kronikol = { ...begin(), at: new Date().toISOString() }
done()
})
})
// Written once the body is parsed, at the time the request arrived; onResponse writes it for one that never got here.
fastify.addHook('preHandler', (request, reply, done) => { writeRequest(request); done() })
fastify.addHook('onSend', (request, reply, payload, done) => {
request.kronikolBody = typeof payload === 'string' ? payload : undefined
done()
})
fastify.addHook('onResponse', (request, reply, done) => {
writeRequest(request)
const { written, at, ...call } = request.kronikol
// Timed once the service's own onResponse hooks have run, so the spans of its response work are the call's.
setImmediate(() => write({ ...call, type: 'Response', method: request.method, uri: uri(request), serviceName: SERVICE, callerName: 'Test',
statusCode: String(reply.statusCode), content: request.kronikolBody, timestamp: new Date().toISOString() }))
done()
})
}
dc.subscribe('fastify.initialization', onFastify)
// Outbound: what MSW sees, mocked or passed through. name maps a host to the service it stands for.
function captureMsw (server, name = host => host) {
const calls = new Map()
server.events.on('request:start', async ({ request, requestId }) => {
const at = new Date().toISOString()
const call = { ...begin(), method: request.method, uri: request.url, serviceName: name(new URL(request.url).host), callerName: SERVICE }
calls.set(requestId, call)
const content = await request.clone().text()
write({ ...call, type: 'Request', content: content || undefined, timestamp: at })
})
// testDouble names what answered in the service's place: MSW, for a call it mocked. A call it let through is
// not marked, since what answered it there is not MSW's to say.
const respond = testDouble => async ({ response, requestId }) => {
const call = calls.get(requestId)
if (!call) return
calls.delete(requestId)
const at = new Date().toISOString()
const content = await response.clone().text()
write({ ...call, type: 'Response', statusCode: String(response.status), content: content || undefined, testDouble, timestamp: at })
}
server.events.on('response:mocked', respond('MSW'))
server.events.on('response:bypass', respond(undefined))
}
function stopCapture () {
dc.unsubscribe('fastify.initialization', onFastify)
}
module.exports = { captureMsw, stopCapture }The response line is timed in setImmediate, once the service's own onResponse hooks have started: written in
the hook itself, Mercurius's onSend and onResponse hook spans started after the call's end, and the ingest said
so ("5 of a trace a call carries, which started outside the time of every call carrying it").
The response line of a call MSW answered says so (testDouble, 5.15.0), so kronikol query parties shows a host
every call to which MSW answered as a double, and counts the calls it answered for a host it only sometimes did
(Querying Reports).
A Jest test that calls handler code directly runs the subject in its own process, and the handler's calls carry the
name its trackers were given, which nobody calls: the inference takes it for the test, so --group-by origin reads
them as test (5.20.0). Declare the handler underTest in the parties file (--parties) and they read subject.
An ingested record carries no attribution, so cause reads the nesting alone: a service's calls made inside a call
the test sent it read request, and a declared handler's, which run inside no recorded call, read unknown.
A failed outbound call is a response line with the error's type behind a bang as its statusCode
("!TypeError") and its message in error (a failed call).
This recipe's fakes never failed; the shape is the in-process one.
OpenTelemetry's documented setup gives one span under Jest, the passed-through call's: its instrumentations hook
Node's require, and Jest loads modules through its own registry. What works (plans/INGEST_FIDELITY_PLAN.md S0):
-
Fastify:
@fastify/otelwithregisterOnInitialization: true, which adds its plugin to each instance Fastify announces on the diagnostics channel. The channel is process-wide, so the subscription is undone after each test file (after-env.js), or the next file in the worker fails withFastifyError: The decorator 'opentelemetry' has already been added!. -
GraphQL: the instrumentation's patches applied by hand, through
getModuleDefinitions(), to the modules Jest's ownrequirereturns, before the service loads: Mercurius takesgraphql's functions when it is required. - fetch: undici's instrumentation, which listens on diagnostics channels, as is.
'use strict'
// Spans: an in-memory tracer provider and the instrumentations, applied the way Jest needs. Loaded from a
// setupFiles entry, so it runs in each test file's module registry before the file and the service load.
const { trace, context } = require('@opentelemetry/api')
const { AsyncLocalStorageContextManager } = require('@opentelemetry/context-async-hooks')
const { BasicTracerProvider, InMemorySpanExporter, SimpleSpanProcessor } = require('@opentelemetry/sdk-trace-base')
const { registerInstrumentations } = require('@opentelemetry/instrumentation')
const { UndiciInstrumentation } = require('@opentelemetry/instrumentation-undici')
const { GraphQLInstrumentation } = require('@opentelemetry/instrumentation-graphql')
const { FastifyOtelInstrumentation } = require('@fastify/otel')
// Spans need no test id: a call carries the trace it was made in, and that joins them.
const exporter = new InMemorySpanExporter()
const provider = new BasicTracerProvider({ spanProcessors: [new SimpleSpanProcessor(exporter)] })
const contextManager = new AsyncLocalStorageContextManager()
contextManager.enable()
context.setGlobalContextManager(contextManager)
trace.setGlobalTracerProvider(provider)
// Fastify announces each new instance on a diagnostics channel; registerOnInitialization adds the plugin to it.
// The channel is process-wide, so the subscription is undone after each test file (after-env.js).
const fastifyOtel = new FastifyOtelInstrumentation({ registerOnInitialization: true })
// undici (global fetch) reports on diagnostics channels too, which Jest's module registry does not hide.
registerInstrumentations({ tracerProvider: provider, instrumentations: [new UndiciInstrumentation(), fastifyOtel] })
// The GraphQL instrumentation hooks Node's require, which Jest bypasses: apply its patches to the modules
// Jest's own require returns, before the service is loaded (Mercurius takes graphql's functions when required).
const graphql = new GraphQLInstrumentation({ mergeItems: true })
graphql.setTracerProvider(provider)
for (const definition of graphql.getModuleDefinitions()) {
const version = require(`${definition.name}/package.json`).version
if (definition.patch) definition.patch(require(definition.name), version)
for (const file of definition.files ?? []) file.patch(require(file.name), version)
}
module.exports = { exporter, fastifyOtel }setupFiles runs in each test file's module registry before the file. setupFilesAfterEnv has afterAll and
expect: after each test file it writes the file's spans as one line (JsonTraceSerializer is what OpenTelemetry's
OTLP/HTTP JSON exporter sends) and undoes the process-wide subscriptions, and it wraps expect so each matcher call
is an assertion record whose text is the test's own line.
'use strict'
// Jest setupFiles: the spans first, so their instrumentation is in place before anything loads the service.
require('./tracing')
require('./capture')'use strict'
// Jest setupFilesAfterEnv: every expect becomes an assertion note; when the test file ends, its spans become one
// OTLP/JSON line of spans-<worker>.jsonl, and the process-wide subscriptions are undone so the next file in this
// worker starts clean.
const fs = require('node:fs')
const path = require('node:path')
const { JsonTraceSerializer } = require('@opentelemetry/otlp-transformer')
const { exporter, fastifyOtel } = require('./tracing')
const { stopCapture } = require('./capture')
const dir = process.env.KRONIKOL_DIR ?? 'kronikol-capture'
afterAll(() => {
const spans = exporter.getFinishedSpans()
if (spans.length > 0) {
fs.mkdirSync(dir, { recursive: true })
const line = Buffer.from(JsonTraceSerializer.serializeRequest(spans)).toString('utf8')
fs.appendFileSync(path.join(dir, `spans-${process.env.JEST_WORKER_ID ?? '1'}.jsonl`), line + '\n')
}
exporter.reset()
fastifyOtel.disable()
stopCapture()
})
// Each matcher call an assertion: its text the test's own line (expect(…).toBe(…)), its place that line's.
const plain = text => String(text).replace(/\u001b\[[0-9;]*m/g, '')
function callSite () {
for (const frame of new Error().stack.split('\n').slice(2)) {
const at = /\(?([^()\s]+):(\d+):\d+\)?$/.exec(frame)
if (!at || at[1].includes('node_modules') || at[1] === __filename || at[1].startsWith('node:')) continue
const line = fs.readFileSync(at[1], 'utf8').split('\n')[Number(at[2]) - 1]?.trim()
return { text: line, sourceFile: path.relative(process.cwd(), at[1]).split(path.sep).join('/'), sourceLine: Number(at[2]) }
}
return { text: 'assertion' }
}
function note (site, error) {
if (!globalThis.__kronikolTestId) return
fs.appendFileSync(path.join(dir, 'tests.ndjson'), JSON.stringify({
event: 'assertion', testId: globalThis.__kronikolTestId, attempt: globalThis.__kronikolAttempt, ...site,
status: error ? 'failed' : 'passed', error: error ? plain(error.message) : undefined, timestamp: new Date().toISOString()
}) + '\n')
}
function noting (matchers, site) {
return new Proxy(matchers, {
get (target, property, receiver) {
const value = Reflect.get(target, property, receiver)
if (property === 'not' || property === 'resolves' || property === 'rejects') return noting(value, site)
if (typeof value !== 'function') return value
return (...args) => {
let result
try {
result = value.apply(target, args)
} catch (error) {
note(site, error)
throw error
}
if (typeof result?.then !== 'function') {
note(site)
return result
}
return result.then(r => { note(site); return r }, error => { note(site, error); throw error })
}
}
})
}
globalThis.expect = new Proxy(globalThis.expect, {
apply: (target, thisArg, args) => noting(Reflect.apply(target, thisArg, args), callSite())
})A test that imports expect from @jest/globals gets Jest's own, which the wrapper does not reach. Every expect
becomes a note in the diagram; the report's Show/Hide Assertions toggle hides them, or note can write failures
only.
The one line outside the harness: wherever the suite's MSW server is set up, pass it to captureMsw, with the names
the diagram gives each faked host.
const { captureMsw } = require('../kronikol/capture')
captureMsw(msw, host => ({ 'psp.example.test': 'PSP' })[host] ?? 'Risk')Name the service under test in the environment (KRONIKOL_SERVICE=Payments GraphQL); it is Service otherwise.
NODE_OPTIONS=--experimental-vm-modules npx jest
kronikol ingest kronikol-capture --tests kronikol-capture/tests.ndjson --spans kronikol-capture --separate-setup -o Reports--spans given a directory takes the files in it that hold spans, so one folder holds all three kinds; the
interaction captures are the rest. --separate-setup draws the calls made in beforeEach inside a Setup
partition. The recipe's run printed:
Spans: 87 span(s) from 1 file(s):
Spans supplied to the ingest: 87 span(s).
Replayed 32 interaction record(s) into 2 scenario(s).
Other: 8 interaction record(s) of earlier attempts of retried tests left out: a retried test's scenario shows its last attempt, its retry badge counting the earlier ones.
Other: 31 supplied span(s) are in no call's internal flow: 31 of a trace no call carries (graphql.parseSchema, graphql.parse, graphql.validate, …).
The 31 spans are the retried test's first attempt's (its calls were left out with it) and the three Fastify instances' schema parses at start-up, which belong to no call.
- Each scenario's sequence diagram:
Test→ the service →PSPandRisk, a step bar per step, thebeforeEachcall in a Setup partition, a ✓ note perexpect. - On every arrow the internal-flow link: the GraphQL call's popup holds the request's 17 spans (Fastify's hooks and
handler, the GraphQL parse, validate and operation, the resolver and every field), as an activity diagram with a
swimlane per instrumentation (
@fastify/otel,@opentelemetry/instrumentation-graphql) and as a flame chart; the call toPSPshows the spans that ran in its time. - The scenario's Activity Diagrams and Flame Chart tabs: the test's whole flow, every span of its traces.
- The retried test as its second attempt, labelled
retry 1, with its source file.
-
Running the service under Jest on Node 22 needed three things unrelated to Kronikol, which a suite that already
runs has solved: MSW pinned to 2.11 (later versions depend on the ESM-only
rettime),content-dispositionoverridden to 0.5.4, and--experimental-vm-modules(Mercurius loads a dependency with a dynamicimport()). -
Clocks. The harness's
Date.now()and the spans' start times agreed to within a millisecond; internal flow takes a span from 50 ms before a call's request to its response, less those of the 50 ms that step 3 of How It Works gives to other calls. -
Concurrency. Tests of one file run one at a time, so the test id on the global is the running test's; the
AsyncLocalStoragescope keeps a request's test however late its work runs.test.concurrentwould need the id in a scope of its own. -
Named steps (
step('When the card is charged')between sections of a test, closing one step and opening the next) are the one addition that touches tests; this recipe's steps are the lifecycle's.
-
Ingesting External Captures: the formats,
kronikol ingest's flags, and how spans join calls - Marking New and Changed Tests: marking the tests a pull request added or edited, as your own detector found them
- Internal Flow Tracking: the popups and the whole-test flow, in-process and ingested
- Integration Otlp Extension: the OTLP reader the command uses
Home · 🔍 Search this wiki Full-text search across every page. The “Pages” list above matches page and heading names, not page content.
Getting Started
- Quick Start (xUnit)
- Project Templates
- AI Integration Prompt
- Framework Integration Guides
- Migrating to v5
- Migrating to v4
Common Tasks
Integration Guides
- Integration xUnit3
- Integration xUnit2
- Integration NUnit
- Integration MSTest
- Integration TUnit
- Integration BDDfy xUnit3
- Integration LightBDD xUnit2
- Integration LightBDD xUnit3
- Integration LightBDD TUnit
- Integration ReqNRoll xUnit2
- Integration ReqNRoll xUnit3
- Integration ReqNRoll TUnit
- Integration Playwright
Uninstrumentable / polyglot backends
- Integration ProxyTap Extension
- Integration TcpTap Extension
- Integration Otlp Extension
- Exporting to OpenTelemetry
- Ingesting External Captures
- Ingesting from Jest
- Integration Cucumber Messages
- Capture-Time Redaction
Extensions
- Integration AtlasDataApi Extension
- Integration BigQuery Extension
- Integration Bigtable Extension
- Integration BlobStorage Extension
- Integration ClickHouse Extension
- Integration CloudStorage Extension
- Integration CosmosDB Extension
- Integration Dapper Extension
- Integration DynamoDB Extension
- Integration EF Core Relational Extension
- Integration Elasticsearch Extension
- Integration EventBridge Extension
- Integration EventHubs Extension
- Integration Grpc Extension
- Integration Kafka Extension
- Integration MassTransit Extension
- Integration MongoDB Extension
- Integration MySqlConnector Extension
- Integration Npgsql Extension
- Integration Oracle Extension
- Integration PubSub Extension
- Integration Redis Extension
- Integration S3 Extension
- Integration ServiceBus Extension
- Integration SNS Extension
- Integration Spanner Extension
- Integration SqlClient Extension
- Integration Sqlite Extension
- Integration SQS Extension
- Integration StorageQueues Extension
- Integration OpenTelemetry Extension
- Integration DispatchProxy Extension
- Integration MediatR Extension
- Integration PlantUML IKVM
Configuration
- Tracking Dependencies
- Tracking Custom Dependencies
- HTTP Tracking Setup
- Report Configuration
- Diagram Customisation
- Phase-Aware Tracking
- Content Formatting
- PlantUML Server Configuration
Features
- Generated Reports
- Report Themes
- Search and Filter Syntax
- Component Diagrams
- PlantUML Browser Rendering
- Inline SVG Rendering
- Internal Flow Tracking
- Tags and Attributes
- Excluding Requests
- Excluded Headers
- Multi-Host Test Architectures
- Event-Driven Architecture Testing
- Service Bus Tracking Patterns
- Background Thread Correlation
- Parallel-Safe Background Correlation
- Event & Message Tracking
- Assertion Tracking
- Step Tracking
- Tabular Attributes
- Large Response and Diagram Handling
- Querying Reports
- Service Card
- Cross-Run History
- Diagnostics and Debugging
- CI Summary Integration
- CI Artifact Upload
- Merging Parallel Reports
Reference