JavaScript API

In addition to providing a command-line utility (odz), One Double Zero also provides a JavaScript API that exposes its internals.

The most important part of those internals is the function getCoverageMap that, given a process coverage, generates and returns the coverage map of a list of source files. From this coverage map, it is possible to get the individual source file coverages, execute a reporter and get a coverage summary, among other things.

Note that the JavaScript API doesn’t expose any way to collect the process coverage. The responsibility of collecting this data is left to the implementations. Typically, the command-line utility odz constructs the process coverage from the V8 coverage data collected by Node.js, but another implementation could totally use a different way to construct the process coverage.

Please read the JavaScript API Reference for more information.

Recipes

Writing your own application

It is very easy to write a custom application that uses One Double Zero JavaScript API. Here is a code sample that gets the coverage map of some sources and, then, outputs the raw coverage summary to the terminal.

import {createOneDoubleZero} from "one-double-zero";
import {readdirSync, readFileSync} from "fs";

const {getCoverageMap} = createOneDoubleZero(
    console.info,
    readdirSync,
    readFileSync
);

const processCoverage = {
  scriptCoverages: [
      // ...
  ]
};

getCoverageMap(['src/main/source-a.ts'], processCoverage)
    .then((coverageMap) => {
        console.log(coverageMap.getCoverageSummary().toJSON());
    });

Writing your own reporter

Writing a custom reporter is equally simple. Here is a code sample that gets the coverage map of some sources and, then, reports it through a custom reporter.

import {createOneDoubleZero} from "one-double-zero";
import {readdirSync, readFileSync, writeFileSync} from "fs";
import {join} from "path";

const {getCoverageMap, report} = createOneDoubleZero(
    console.info,
    readdirSync,
    readFileSync
);

const processCoverage = {
    scriptCoverages: [
        // ...
    ]
};

/** @type {import("one-double-zero").Reporter} */
const reporter = {
  name: 'foo',
  execute: (context) => {
      writeFileSync(
          join(context.outputDirectory, 'foo-summary.json'),
          JSON.stringify(context.coverageMap.getCoverageSummary().toJSON())
      );
  }  
};

getCoverageMap(['src/main/source-a.ts'], processCoverage)
    .then((coverageMap) => {
        return report(coverageMap, [reporter], './reports');
    });