Skip to content

chore: adding test-consumer documentation #25

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 1, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 67 additions & 0 deletions src/content/docs/reference/test-consumer.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
---
title: '@metrics/test-consumer'
---

This module is a memory based consumer for metrics streams to be used in tests. The purpose of the module is to make writing tests and asserting metrics easier.
It takes a metric stream generated by @metrics/client and makes the collected metrics available as an array.

⚠️ You should _never_ use this in produciton code, however it is very convenient when writing tests which produce metrics using [`@metrics/client`](https://metrics-js.github.io/reference/client/)

## Examples usage

Below is a sample test showing how this could be used:

```js
const test = require('tap');
const Metrics = require('@metrics/client');
const TestConsumer = require('@metrics/test-consumer');

test('some test case', async () => {
const metrics = new Metrics();
// This sets up the metrics client to be used
const testHelper = new TestConsumer(metrics)
// .start sets up the stream
testHelper.start();

// Code which triggers a count metric

testHelper.stop(); // .stop ends the streams and now we can get the result.

testHelper.getResults().then(result => {
t.equal(result.name, "some_counter"); // Validate our metrics was collected
res.labels.forEach((metricLabel) => {
if (metricLabel.name === "value") {
t.equal(metricLabel.value, 2); // We expect two counts to have happened
}
});
});
});
```

## API

- [constructor](#constructormetrics)
- [start](#start)
- [stop](#stop)
- [getResults](#async-getresults)
- [createMetrics](#createmetrics)

### constructor(metrics)

Takes in the [@metrics/client](https://metrics-js.github.io/reference/client/) to collect metrics from.

### .start()

Creates a readable stream which listens for metrics produced by the client.

### .stop()

Ends the stream setup for the client, returns a Promise which resolves to an array with the metrics consumed.

### async .getResults()

Returns a promise which resolves to an array containing collected `[@metrics/metrics](https://metrics-js.github.io/reference/metric/)` objects.

### createMetrics

Utility object with functions for creating mock `Metric` objects, has the functions `.timer` and `.counter`.