test-snippets
v2.0.2
Published
Flexibly test markdown code examples
Downloads
254
Maintainers
Readme
test-snippets
Flexibly test markdown code examples.
A command to extract and run tagged examples in markdown files, and test them against your NPM package.
Your node package is built locally and installed in a subdirectory (by default tests/snippets
).
Installation
npm install test-snippets
Usage
You will need a config file, the default config file location is tests/snippets/config.json
. This file specifies how to run the snippets.
Take this config file for example:
{
"es6": { "command": ["node"], "extension": "js" },
"js": { "command": ["node"], "extension": "cjs" },
"ts": { "command": ["tsx"], "extension": "ts" }
}
This allows you to tag snippets with "es6", "js" or "ts" in your markdown. Add an HTML comment directly above a code block, using any tags you wish to run it with (separated by commas):
<!-- snippet: es6,ts -->
```js
import path from 'path';
console.log(path.join('hello', 'world'));
```
To run the command use:
npx test-snippets
This will look through all .md
files in the repository (excluding anything in node_modules folders) then locally install the NPM package and run the snippets with it. By default it will use tests/snippets
as the test directory.
You can choose specific files:
npx test-snippets README.md hello.md
Or use glob rules:
npx test-snippets "docs/**/*.md"
You can override the ignored files, as a comma separated list:
npx test-snippets "**/*.md" --ignore="README.md,hello.md"
You can override the config file:
npx test-snippets --config=config.json
You can override the test directory:
npx test-snippets --test-dir=test-dir/
Debugging
Test artifacts will be automatically cleaned up, however, you can disable cleanup of tests with the cleanup
option:
npx test-snippets --cleanup=false
This will leave the files
and node_modules
directories in the test directory. This can be useful when debugging failing tests, you can run the code yourself or even debug the installed node module.
Programmatic usage
Call with a list of files, a config file and a directory
import testSnippets from 'test-snippets';
(async () => {
await testSnippets(['file.md', 'other.md'], 'config.json', 'test-dir/', true);
})();
With CommonJS / require()
const testSnippets = require('test-snippets');
(async () => {
await testSnippets(['file.md', 'other.md'], 'config.json', 'test-dir/', true);
})();