open-index/open-npm huggingface dataset:
npm package: @metrics/test-consumer
Description: A in memory metrics consumer intended for use in tests with @metrics/client metric streams
Author: Espen Dalløkken
Latest version: 3.0.1

# @metrics/test-consumer

[![Dependencies](https://img.shields.io/david/metrics-js/test-consumer.svg)](https://david-dm.org/metrics-js/test-consumer)
[![GitHub Actions status](https://github.com/metrics-js/prometheus-consumer/workflows/Run%20Lint%20and%20Tests/badge.svg)](https://github.com/metrics-js/test-consumer/actions?query=workflow%3A%22Run+Lint+and+Tests%22)
[![Known Vulnerabilities](https://snyk.io/test/github/metrics-js/prometheus-consumer/badge.svg?targetFile=package.json)](https://snyk.io/test/github/metrics-js/test-consumer?targetFile=package.json)

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 assert = require("node:assert");
const { test } = require("node:test");
const MetricsClient = require("@metrics/client");
const TestConsumer = require("@metrics/test-consumer");

test("some test case", async () => {
	// Pass in the metrics client you want to consume.
	const metrics = new MetricsClient();
	const testHelper = new TestConsumer(metrics);
	// Sets up the consumer to capture events.
	testHelper.start();

	// 👋 Your code which produces some kind of metric goes here.

	// Ends the streams, now we can get the result.
	testHelper.stop();

	const result = await testHelper.getResults();
	const metric = result.find((m) => m.name === "some_counter");

	assert.ok(metric, "Expected to find metric some_counter");
	assert.equal(metric.value, 2);
});
```

## API

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

### 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.