Files
gen-doctests/README.md
T
2026-07-04 22:44:43 +02:00

1.8 KiB

gen-doctests

Generate tests from your JSDoc documentation for whichever testing harness you prefer.

Usage

See gen-doctests --help for more detail.

Generate tests

Write a doctest alongside your source code:

// src/isEven.ts

/**
 * Returns whether the specified number is divisible by 2
 * @param x The number to check
 * @example
 * ```ts
 * expect(isEven(5)).toBe(false);
 * expect(isEven(4)).toBe(true);
 * ```
 */
export function isEven(x: number) {
	return x % 2 === 0;
}

And generate your doctests using either the library or the CLI:

$ gen-doctests src/**.ts --format vitest -o tests/generated

With the above produces the following test file:

// tests/generated/isEven.doc.test.ts

// Automatically generated tests for ../../src/isEven.ts

import { describe, expect, test, vi } from "vitest";
import { isEven } from "../../src/isEven";

test("isEven()", () => {
	expect(isEven(5)).toBe(false);
	expect(isEven(4)).toBe(true);
});

Config

You can also define a doctests.config.ts file to skip the command arguments:

// doctests.config.ts
import { defineConfig } from "gen-doctests/config";

export default defineConfig({
	include: ["src/**.{js,jsx,ts,tsx}"],
	outDir: "dist/",
});

Skipping tests

You can specify that a test should be ignored or that it fails by specifying that next to the language tag of the code block:

/**
 * ...
 * @example
 * ```ts ignore
 * // this test is ignored
 * ```
 * @example
 * ```ts fails
 * // this test is expected to fail
 * expect(1).toBe(2)
 * ```
 */

If you use the --must-assert flag or onlyGenerateTests option then tests which do not use any assertions will not be included in emitted test files.

License

Published under MIT License